import { Button, Table } from 'antd'
import { useImmer } from 'use-immer';
function App () {
// 使用useImmer管理表格数据源,支持不可变数据操作
const [dataSource, setDataSource] = useImmer([
{
key: '1', // 数据唯一标识
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号',
},
])
// 表格列配置
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
id: 1 // 内部标识
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
id: 2
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
id: 3
},
{
title: '操作',
dataIndex: 'bind',
key: 'bind',
// 渲染操作按钮
render: (_: any, record: any) => {
console.log(record) // 打印当前行数据
return (
<Button type="primary" danger onClick={() => handleClick(record.key)}>删除</Button>
)
}
},
];
// 处理删除操作
const handleClick = (key: any) => {
// 使用immer的draft模式更新数据
setDataSource((draft) => {
// 查找要删除的数据索引
const index = draft.findIndex((item) => item.key === key)
// 从数组中删除对应项
draft.splice(index, 1)
})
}
return <div>
{/* 渲染Ant Design表格,传入数据源和列配置 */}
<Table dataSource={dataSource} columns={columns} />;
</div>
}
export default App
React中 Ant Design的表格基础使用
最新推荐文章于 2025-06-07 16:45:08 发布