参考链接:https://zhuanlan.zhihu.com/p/68113130
antd 有自带的可编辑table,但是用着不太顺手,自己写了一个,为了后期维护方便,把可编辑块提取一个函数,随用随取。
import React, { Component } from 'react'; import { connect } from 'dva';
import { Card, Table, Form, Popconfirm, Input, message, Row, Col, Modal, Button, DatePicker, InputNumber } from "antd";
const FormItem = Form.Item;
@Form.create()
export default class EditableTable extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [ { name: '张三', age: '32', address: '北京市朝阳区', }, { name: '李四', age: '58', address: '北京市西城区', }, ], };
}
save = (name, record, row, index, e) => {
this.props.form.validateFields((error, values) => {
if (error && error[e.currentTarget.id]) return;
const newData = [...this.state.dataSource]; newData[index][name] = e.currentTarget.value; this.setState({ dataSource: newData }); console.log(this.state.dataSource) });
};
handleDelete = (row) => { console.log(row) };
onCancle = () => {
this.props.dispatch(routerRedux.push(`/WisdomSale/SmartSale/TaskList`));
};
// 新建任务 saveTable = () => {
const that = this;
that.props.form.validateFields((err, payload) => { console.log(payload); });
};
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
const editCol = (name, record, row, index) => {
return (
<FormItem>
{getFieldDecorator( `${name}${index}` ,
{ rules: [{ required: true, message: `请输入合理参数` }], initialValue: record, })(
<Input onBlur={this.save.bind(this, name, record, row, index)} />)} </FormItem> );
};
const columns = [ {
title: '姓名', dataIndex: 'name', width: '30%', },
{ title: '年龄', dataIndex: 'age', render: (record, row, index) => { return editCol('age', record, row, index); } },
{ title: '地址', dataIndex: 'address', },
{ title: '操作', dataIndex: 'operation',
render: (record, row) => {
<Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(row)}> <a href="javascript:;">删除</a> </Popconfirm>
},
];
return (
<Form>
<Table rowKey="id" bordered dataSource={this.state.dataSource} columns={columns} />
<div style={{ textAlign: 'center' }}>
<Button onClick={this.onCancle} style={{ margin: '10px' }}>取消</Button>
<Button type="primary" onClick={this.saveTable}>保存</Button>
</div>
</Form>
); }
}