antdpro的可编辑表格
时间: 2023-10-02 22:13:29 浏览: 173
可编辑的表格
5星 · 资源好评率100%
Ant Design Pro 提供了一个可编辑表格的组件,名为 EditableTable,可以轻松地实现表格数据的编辑和保存。下面是一个简单的例子:
```jsx
import { useState } from 'react';
import { Button, Table, Input } from 'antd';
const EditableTable = () => {
const [data, setData] = useState([
{ id: 1, name: 'John', age: 24 },
{ id: 2, name: 'Mary', age: 32 },
{ id: 3, name: 'Bob', age: 45 },
]);
const handleSave = (row) => {
const newData = [...data];
const index = newData.findIndex((item) => row.id === item.id);
newData[index] = row;
setData(newData);
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
editable: true,
},
{
title: 'Age',
dataIndex: 'age',
editable: true,
},
{
title: 'Action',
render: (_, row) => (
<Button type="primary" onClick={() => handleSave(row)}>
Save
</Button>
),
},
];
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
const EditableRow = ({ index, ...restProps }) => (
<Table.Row {...restProps} />
);
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false);
const [inputValue, setInputValue] = useState(children);
const toggleEdit = () => {
setEditing(!editing);
setInputValue(record[dataIndex]);
};
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleBlur = () => {
setEditing(false);
handleSave({ ...record, [dataIndex]: inputValue });
};
return (
<td {...restProps}>
{editable ? (
editing ? (
<Input value={inputValue} onChange={handleChange} onBlur={handleBlur} />
) : (
<div style={{ paddingRight: 24 }} onClick={toggleEdit}>
{children}
</div>
)
) : (
children
)}
</td>
);
};
return (
<Table
bordered
dataSource={data}
columns={columns}
components={components}
rowKey="id"
/>
);
};
export default EditableTable;
```
注意,这个例子中使用了 antd 的 Input 和 Button 组件,如果没有安装 antd,需要先安装才能运行。另外,这个例子还使用了 React Hooks 实现了组件的状态管理。
阅读全文