基于antd edit table二次改造支持所有单元格编辑及校验
以下是一个使用Ant Design的Table
组件进行二次改造,以支持所有单元格编辑和验证的基本示例。这个例子使用React和TypeScript。
import React, { useState } from 'react';
import { Table, Input, Button, Popconfirm, Form } from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
interface DataType {
key: string;
name: string;
age: number;
address: string;
}
const EditableTable: React.FC = () => {
const [form] = Form.useForm();
const [data, setData] = useState<DataType[]>([
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
// ... more data
]);
const handleDelete = (key: React.Key) => {
setData(data.filter((item) => item.key !== key));
};
const handleSave = (row: DataType) => {
const newData = [...data];
const index = newData.findIndex((item) => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, {
...item,
...row,
});
setData(newData);
};
const columns = [
{
title: 'name',
dataIndex: 'name',
key: 'name',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
key: 'age',
editable: true,
},
{
title: 'address',
dataIndex: 'address',
key: 'address',
editable: true,
},
{
title: 'operation',
dataIndex: 'operation',
render: (text, record) => (
<span>
<Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.key)}>
<MinusCircleOutlined style={{ marginRight: 8 }} />
</Popconfirm>
<Form form={form} component={false}>
<Button
type="link"
onClick={() => {
form.setFieldsValue({ [record.key]: record });
}}
>
<PlusCircleOutlined />
</Button>
</Form>
</span>
),
},
];
return (
<div>
<Table
components={{
body: {
cell: EditableCell,
},
}}
bordered
dataSource={data}
columns={columns}
rowClassName="editable-row"
pagination={{
onChange: (page) => {
console.log(page);
},
pageSize: 5,
}}
/>
评论已关闭