react antd表格中如何进行编辑
使用 Form 和 Table 结合实现编辑
在 Table 的 columns 中,通过 render 方法动态切换显示和编辑状态。编辑状态时,使用 Form.Item 包裹输入组件(如 Input 或 Select),并通过 form.setFieldsValue 和 form.getFieldsValue 管理数据。

import { Table, Input, Button, Form } from 'antd';
const EditableTable = () => {
const [form] = Form.useForm();
const [editingKey, setEditingKey] = useState('');
const [data, setData] = useState(initialData);
const isEditing = (record) => record.key === editingKey;
const edit = (record) => {
form.setFieldsValue({ ...record });
setEditingKey(record.key);
};
const save = async (key) => {
try {
const values = await form.validateFields();
const newData = [...data];
const index = newData.findIndex((item) => key === item.key);
newData[index] = { ...newData[index], ...values };
setData(newData);
setEditingKey('');
} catch (err) {
console.error('Validate Failed:', err);
}
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
render: (_, record) => {
if (isEditing(record)) {
return (
<Form.Item name="name" rules={[{ required: true }]}>
<Input />
</Form.Item>
);
}
return record.name;
},
},
{
title: 'Action',
render: (_, record) => {
if (isEditing(record)) {
return (
<Button onClick={() => save(record.key)} type="primary">
Save
</Button>
);
}
return <Button onClick={() => edit(record)}>Edit</Button>;
},
},
];
return (
<Form form={form} component={false}>
<Table columns={columns} dataSource={data} />
</Form>
);
};
使用 editable 属性实现行内编辑
通过 Table 的 components 属性自定义单元格为可编辑状态。结合 onCell 方法动态控制编辑行为,适用于行内直接修改的场景。
import { Table, Input } from 'antd';
const EditableCell = ({ editing, dataIndex, children, ...restProps }) => {
return (
<td {...restProps}>
{editing ? (
<Input defaultValue={children[1]} />
) : (
children
)}
</td>
);
};
const EditableTable = () => {
const [editingKey, setEditingKey] = useState('');
const columns = [
{
title: 'Name',
dataIndex: 'name',
onCell: (record) => ({
editing: record.key === editingKey,
dataIndex: 'name',
}),
},
{
title: 'Action',
render: (_, record) => (
<Button onClick={() => setEditingKey(record.key)}>
Edit
</Button>
),
},
];
return (
<Table
components={{ body: { cell: EditableCell } }}
columns={columns}
dataSource={data}
/>
);
};
使用 pro-table 快速实现编辑
若项目中使用 @ant-design/pro-table,可直接通过 editable 属性配置表格编辑功能,无需手动管理状态。
import ProTable from '@ant-design/pro-table';
const EditableTable = () => {
return (
<ProTable
columns={[
{ title: 'Name', dataIndex: 'name', editable: true },
{ title: 'Age', dataIndex: 'age', editable: true },
]}
value={data}
editable={{
onSave: async (key, row) => {
console.log(key, row);
},
}}
/>
);
};
注意事项
- 表单验证:通过
Form.Item的rules属性定义校验规则,确保数据合法性。 - 性能优化:大数据量时,避免频繁渲染,可通过
shouldUpdate或memo优化组件。 - 数据同步:编辑后需手动更新数据源,避免直接修改原始数据。







