antd获取table中checkbox选中的值
时间: 2023-10-02 10:06:28 浏览: 316
可以通过antd的`Table`组件中的`rowSelection`属性来实现多选和单选功能,并通过`selectedRowKeys`属性来获取当前选中的行的key值。
具体实现步骤如下:
1. 在`<Table>`组件中添加`rowSelection`属性,设置`type`为`checkbox`表示启用多选功能。
```
<Table
rowSelection={{
type: "checkbox",
onChange: this.onSelectChange,
selectedRowKeys: this.state.selectedRowKeys
}}
columns={columns}
dataSource={data}
/>
```
2. 在`<Table>`组件中添加`onChange`事件处理函数`onSelectChange`。
```
onSelectChange = (selectedRowKeys, selectedRows) => {
this.setState({ selectedRowKeys });
};
```
3. 在`render()`函数中获取当前选中行的key值。
```
const { selectedRowKeys } = this.state;
```
完整示例代码如下:
```
import React from "react";
import ReactDOM from "react-dom";
import { Table } from "antd";
const columns = [
{
title: "Name",
dataIndex: "name"
},
{
title: "Age",
dataIndex: "age"
},
{
title: "Address",
dataIndex: "address"
}
];
const data = [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park"
},
{
key: "2",
name: "Jim Green",
age: 42,
address: "London No. 1 Lake Park"
},
{
key: "3",
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park"
},
{
key: "4",
name: "Jim Red",
age: 32,
address: "London No. 2 Lake Park"
}
];
class App extends React.Component {
state = {
selectedRowKeys: []
};
onSelectChange = (selectedRowKeys, selectedRows) => {
this.setState({ selectedRowKeys });
};
render() {
const { selectedRowKeys } = this.state;
const rowSelection = {
type: "checkbox",
onChange: this.onSelectChange,
selectedRowKeys
};
return (
<Table
rowSelection={rowSelection}
columns={columns}
dataSource={data}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
```
阅读全文