import { Table, InputNumber, Button } from 'antd';
import React from 'react';
const EditableContext = React.createContext();
class EditableCell extends React.Component {
renderCell = () => {
const {
dataIndex,
rowIndex,
title,
inputType,
record,
index,
children,
isEdit,
data,
...restProps
} = this.props;
return (
// 单元格判断
<td {...restProps}>
{isEdit ? (
// 这里可自行修改,项目需要数组输入框
<InputNumber defaultValue={data[rowIndex][dataIndex]} onChange={ (value)=> { return this.onChange(value,rowIndex,dataIndex )}} />
) : (
children
)}
</td>
);
};
onChange = (value, rowIndex,dataIndex) => {
// 表格变化走父组件方法
this.props.handChange(value, rowIndex,dataIndex)
};
render() {
return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
}
}
class EditableTable extends React.Component {
constructor(props) {
super(props);
this.state = { editingKey: '', isEdit: false, temData: [] };
this.columns = [
{
title: 'name',
dataIndex: 'name',
width: '25%',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
width: '20%',
editable: true,
},
];
}
handEdit() {
this.setState({ isEdit: true });
}
handCancle() {
this.setState({ isEdit: false });
}
handChange = (value, rowIndex,dataIndex) => {
let otherData = JSON.parse(JSON.stringify(this.state.temData))
otherData[rowIndex][dataIndex] = value
this.setState({ temData: JSON.parse(JSON.stringify(otherData))});
}
componentDidMount() {
this.setState({ temData: JSON.parse(JSON.stringify(this.props.data)) });
}
render() {
const components = {
body: {
cell: EditableCell,
},
};
const columns = this.columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record, rowIndex) => ({
record,
rowIndex,
dataIndex: col.dataIndex,
title: col.title,
isEdit: this.state.isEdit,
data: this.props.data,
handChange: this.handChange
}),
};
});
return (
<div>
<Table
components={components}
bordered
dataSource={this.props.data}
columns={columns}
rowClassName="editable-row"
pagination={false}
/>
{this.state.isEdit ?<Button onClick={() => this.handCancle()}>取消</Button>
: <Button type="primary" onClick={() => this.handEdit()}>编辑</Button> }
</div>
);
}
}
export default EditableTable
父组件通过绑定ref获取子组件修改后的表格
import EditTable from './components/EditTable'
function testPage() {
const getData = () => {
console.log(myRef)
}
let myRef = null;
const data = [];
for (let i = 0; i < 6; i++) {
data.push({
key: i.toString(),
name: i,
age: 32,
});
}
return(
<EditTable ref={(r) => (myRef = r)} data={data}></EditTable>
<button onClick={getData}>获取</button>
)
}
效果如下:
点击编辑开启编辑模式
点击获取可看到temData值已经被修改,后续可自行进行操作