这个是根据antd自己改装的 类组件实现表格的行编辑
import { Form, Input, InputNumber, Popconfirm, Table, Typography } from 'antd';
import React, { useState,Component } from 'react';
const originData = [];
for (let i = 0; i < 3; i++) {
originData.push({
key: i.toString(),
name: `Edrward ${i}`,
age: 32,
address: `London Park no. ${i}`,
});
}
const EditableCell = ({
editing,
dataIndex,
title,
inputType,
record,
index,
children,
...restProps
}) => {
const inputNode = inputType === 'number' ? : ;
return (
{editing ? (
{inputNode}
) : (
children
)}
);
};
export default class App extends Component{
state={
data:originData,
editingKey:'',
load:false
}
// 是否编辑
isEditing = record => record.key === this.state.editingKey;
// 编辑
edit = async (record) => {
this.setState({
editingKey:record.key
})
this.form.setFieldsValue({
name: '',
age: '',
address: '',
...record,
});
};
// 取消
cancel = () => {
this.setState({
editingKey:''
})
};
// 保存
save = async (key) => {
const {data} = this.state
try {
const row = await this.form.validateFields();
const newData = [...data];
const index = newData.findIndex((item) => key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, {
...item,
...row,
});
this.setState({
data:newData,
editingKey:''
})
} else {
newData.push(row);
this.setState({
data:newData,
editingKey:''
})
}
console.log(newData);
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
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: 'operation',
dataIndex: 'operation',
render: (_, record) => {
const {editingKey} = this.state
let editable = this.isEditing(record);
// 当 有key的时候 才能保存和取消
return editable ? (
this.save(record.key)}
style={{
marginRight: 8,
}}
>
Save
Cancel
) : (
this.edit(record)}>
Edit
);
},
},
];
render(){
const {data,editingKey} = this.state
const columns = this.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),
}),
};
});
return (