import { observable, action, toJS } from ‘mobx’;
class State {
@observable data = [];
@observable columns = [
{
title: ‘name’,
dataIndex: ‘name’,
width: ‘25%’,
editable: true
},
{
title: ‘age’,
dataIndex: ‘age’,
width: ‘15%’,
editable: true
},
{
title: ‘address’,
dataIndex: ‘address’,
width: ‘40%’,
editable: true
},
{
title: ‘edit’,
dataIndex: 'edit
}
];
}
export default new State();
import React from ‘react’;
import { observer } from ‘mobx-react’;
import { Table, Input, InputNumber, Popconfirm, Form } from ‘antd’;
import ‘./index.less’;
import G2 from ‘@antv/g2’;
import state from ‘./index.state’;
for (let i = 0; i < 100; i++) {
state.data.push({
key: i.toString(),
name: Edrward ${i}
,
age: 32,
address: London Park no. ${i}
});
}
const EditableContext = React.createContext();
@observer
class EditableCell extends React.Component {
getInput = () => {
if (this.props.inputType === 'number') {
return ;
}
return ;
};
renderCell = ({ getFieldDecorator }) => {
const {
editing,
dataIndex,
title,
inputType,
record,
index,
children,
...restProps
} = this.props;
return (
{editing ? (
{getFieldDecorator(dataIndex, {
rules: [
{
required: true,
message: `Please Input ${title}!` //判断不能为空,可取消
}
],
initialValue: record[dataIndex]
})(this.getInput())}
) : (
children
)}
);
};
render() {
return {this.renderCell} ;
}
}
@observer
class EditableTable extends React.Component {
constructor(props) {
super(props);
this.state = { editingKey: '' };
}
isEditing = record => record.key === this.state.editingKey;
cancel = () => {
this.setState({ editingKey: '' });
};
//保存方法
save(form, key) {
form.validateFields((error, row) => {
if (error) {
return;
}
const newData = [...state.data];
const index = newData.findIndex(item => key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, {
...item,
...row
});
//。。。row 获取修改的单行数据
state.data = newData;
this.setState({ editingKey: '' });
} else {
newData.push(row);
state.data = newData;
this.setState({ editingKey: '' });
}
});
}
edit(key) {
this.setState({ editingKey: key });
}
//自定义表格内容
doColums = (arr) => {
arr.map((item, index) => {
if (item.dataIndex == 'edit') {
item.render = (text, record) => {
const { editingKey } = this.state;
const editable = this.isEditing(record);
return editable ? (
{form => (
this.save(form, record.key)}
style={{ marginRight: 8 }}
>
保存
)}
this.cancel(record.key)}>
取消
) : (
this.edit(record.key)}>
修改
);
};
}
});
}
render() {
const components = {
body: {
cell: EditableCell
}
};
const columns = state.columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
inputType: col.dataIndex === 'age' ? 'number' : 'text',
dataIndex: col.dataIndex,
title: col.title,
editing: this.isEditing(record)
})
};
});
this.doColums(columns);
return (
);
}
}
const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
效果图:
具体的还是以为官网为主。
antd 官网地址:https://ant.design/components/table-cn/#components-table-demo-edit-row