ant table 如何添加点击事件
时间: 2023-11-16 22:08:58 浏览: 41
Ant Design 中的 Table 组件提供了 `onRow` 属性,可以用于设置行的点击事件。
具体实现步骤如下:
1. 在 Table 组件中添加 `onRow` 属性,并将该属性值设置为一个函数,该函数接受一个参数 `record`,表示当前行的数据记录。
```jsx
<Table dataSource={dataSource} columns={columns} onRow={(record) => ({onClick: () => handleRowClick(record)})} />
```
2. 实现 `handleRowClick` 函数,该函数根据需要处理当前行的点击事件。例如,可以在该函数中弹出一个模态框,显示当前行的详细信息。
```jsx
const handleRowClick = (record) => {
Modal.info({
title: '详细信息',
content: (
<div>
<p>姓名:{record.name}</p>
<p>年龄:{record.age}</p>
<p>地址:{record.address}</p>
</div>
),
});
};
```
完整代码示例:
```jsx
import { Table, Modal } from 'antd';
const dataSource = [
{
key: '1',
name: '张三',
age: 18,
address: '北京市朝阳区',
},
{
key: '2',
name: '李四',
age: 20,
address: '上海市浦东区',
},
];
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '地址',
dataIndex: 'address',
key: 'address',
},
];
const handleRowClick = (record) => {
Modal.info({
title: '详细信息',
content: (
<div>
<p>姓名:{record.name}</p>
<p>年龄:{record.age}</p>
<p>地址:{record.address}</p>
</div>
),
});
};
const MyTable = () => {
return <Table dataSource={dataSource} columns={columns} onRow={(record) => ({onClick: () => handleRowClick(record)})} />;
};
export default MyTable;
```