React+Ant Design實現可編輯單元格、添加行並利用form獲取新增數據

實現如下圖所示需求:
在這裏插入圖片描述
實現功能說明:
點擊添加按鈕,在表格中添加新的空白行(如下圖所示),在點擊提交的時候獲取空白行的數據
在這裏插入圖片描述
在構造函數內定義:

constructor(props) {
    super(props)
    this.state = {
        dataSource:[{
            key: 0,
            name1: '',
            name2: '',
            name3: '',
        }],//應用信息化查詢方法
        count:1,//總數
    }
}

注:如果dataSource定義爲空數組,則頁面初始化時表格沒有輸入框,需要點擊添加行,如下圖
在這裏插入圖片描述
在render()中定義:

const { form: { getFieldDecorator },dataSource } = this.props

在return中添加如下代碼:

<div>
</Form>
<Form.Item>
            <Table 
                columns={[
                    { title: '名稱1', dataIndex: 'name1',render: (text, record, index) => 
                        <Form.Item key={index}>
                            {getFieldDecorator(`tableDt[${index}].name1`)(
                                <Input placeholder="請輸入名稱1" /> 
                            )}
                        </Form.Item>
                    },
                    { title: '名稱2', dataIndex: 'name2',render: (text, record, index) => 
                        <Form.Item key={index}>
                            {getFieldDecorator(`tableDt[${index}].name2`)(
                                <Input placeholder="請輸入名稱2" /> 
                            )}
                        </Form.Item>
                    },
                    { title: '名稱3', dataIndex: 'name3',render: (text, record, index) => 
                        <Form.Item key={index}>
                            {getFieldDecorator(`tableDt[${index}].name3`)(
                                <Input placeholder="請輸入名稱3" /> 
                            )}
                        </Form.Item>
                    },
                ]}
                dataSource={this.state.dataSource}
                pagination={false}
            />
        </Form.Item>

    </Form>
    <Row gutter={16}>
        <Col span={24}>
            <Button onClick={ this.save } type="primary">提交</Button>
            <Button onClick={ this.toback }>返回</Button>
            <span className="tips">{this.state.saveTipCont}</span>
        </Col>
    </Row>
</div>

點擊添加行按鈕的操作方法:
//添加應用信息化查詢方法行

handleRowAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
        key: count,
        name1: '',
        name2: '',
        name3: '',
    };
    this.setState({
        dataSource: [...dataSource, newData],
        count: count + 1,
    });
}

點擊提交操作的方法:

//保存
save = () => {
    //處理校驗值
    this.props.form.validateFields((err, values) => {
        // console.log(values)
        if(!err){
            // values.tableDt就是個表格數據的數組,可對獲取的值進行處理校驗處理
        }
    })
}

實現效果如下:
在這裏插入圖片描述
value.tableDt值如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章