antd table 删除行
时间: 2023-09-04 13:11:56 浏览: 50
可以通过 `antd` 的 `Table` 组件的 `rowSelection` 和 `onDelete` 两个属性来实现删除行的功能。
首先,需要在 `Table` 组件中设置 `rowSelection` 属性,让用户可以选中要删除的行:
```jsx
<Table
dataSource={dataSource}
columns={columns}
rowKey="id"
rowSelection={{
type: 'checkbox',
selectedRowKeys,
onChange: setSelectedRowKeys,
}}
onDelete={handleDelete}
/>
```
其中,`selectedRowKeys` 和 `setSelectedRowKeys` 分别是选中的行的 `key` 值和更新选中行的函数。
然后,需要在 `Table` 组件中设置 `onDelete` 属性,来处理删除行的逻辑:
```jsx
const handleDelete = () => {
const newDataSource = [...dataSource];
selectedRowKeys.forEach((key) => {
newDataSource = newDataSource.filter((item) => item.id !== key);
});
setDataSource(newDataSource);
setSelectedRowKeys([]);
};
```
在上述代码中,我们首先复制原来的数据源 `dataSource`,然后遍历选中的行的 `key` 值,将它们从数据源 `newDataSource` 中删除,最后更新数据源和选中行的状态。
完整代码如下:
```jsx
import { Table } from 'antd';
const columns = [
{
title: 'ID',
dataIndex: 'id',
},
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Age',
dataIndex: 'age',
},
];
const dataSource = [
{
id: '1',
name: 'John Brown',
age: 32,
},
{
id: '2',
name: 'Jim Green',
age: 42,
},
{
id: '3',
name: 'Joe Black',
age: 23,
},
];
const App = () => {
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [dataSource, setDataSource] = useState(dataSource);
const handleDelete = () => {
let newDataSource = [...dataSource];
selectedRowKeys.forEach((key) => {
newDataSource = newDataSource.filter((item) => item.id !== key);
});
setDataSource(newDataSource);
setSelectedRowKeys([]);
};
return (
<Table
dataSource={dataSource}
columns={columns}
rowKey="id"
rowSelection={{
type: 'checkbox',
selectedRowKeys,
onChange: setSelectedRowKeys,
}}
onDelete={handleDelete}
/>
);
};
export default App;
```