ant design 可编辑table 整行可编辑
时间: 2024-04-30 11:15:24 浏览: 153
Ant Design是一基于React的UI组件库提供了丰富的可复用组件和样式,便开发者构建美观、高效的Web应用。其中,Ant Design的Table组件提供了可编辑的功能。
要实现整行可编辑的功能,可以使用Ant DesignTable组件的editable属性。首先,将editable属性设置为true,然后在columns配置中指定需要可编辑的列,并为每一列设置editable属性为true。这样,用户就可以通过双击单元格来编辑表格内容了。
以下是一个示例代码:
```jsx
import React, { useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form } from 'antd';
const EditableCell = ({
editing,
dataIndex,
title,
inputType,
record,
index,
children,
...restProps
}) => {
const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
return (
<td {...restProps}>
{editing ? (
<Form.Item
name={dataIndex}
style={{
margin: 0,
}}
rules={[
{
required: true,
message: `Please Input ${title}!`,
},
]}
>
{inputNode}
</Form.Item>
) : (
children
)}
</td>
);
};
const EditableTable = () => {
const [form] = Form.useForm();
const [data, setData] = useState(dataSource);
const [editingKey, setEditingKey] = useState('');
const isEditing = (record) => record.key === editingKey;
const edit = (record) => {
form.setFieldsValue({
name: '',
age: '',
address: '',
...record,
});
setEditingKey(record.key);
};
const cancel = () => {
setEditingKey('');
};
const save = async (key) => {
try {
const row = await 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 });
setData(newData);
setEditingKey('');
} else {
newData.push(row);
setData(newData);
setEditingKey('');
}
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
const 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 editable = isEditing(record);
return editable ? (
<span>
<a
href="javascript:void(0);"
onClick={() => save(record.key)}
style={{
marginRight: 8,
}}
>
Save
</a>
<Popconfirm title="Sure to cancel?" onConfirm={cancel}>
<a>Cancel</a>
</Popconfirm>
</span>
) : (
<a disabled={editingKey !== ''} onClick={() => edit(record)}>
Edit
</a>
);
},
},
];
const mergedColumns = 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: isEditing(record),
}),
};
});
return (
<Form form={form} component={false}>
<Table
components={{
body: {
cell: EditableCell,
},
}}
bordered
dataSource={data}
columns={mergedColumns}
rowClassName="editable-row"
pagination={{
onChange: cancel,
}}
/>
</Form>
);
};
export default EditableTable;
```
这段代码演示了如何使用Ant Design的Table组件实现整行可编辑的功能。你可以根据自己的需求进行修改和扩展。
阅读全文