当使用类组件时,你可以通过 this.setState 方法来实现相似的功能。以下是使用类组件的例子:
import React, { Component } from 'react';
import { Table, Checkbox } from 'antd';
class YourComponent extends Component {
constructor(props) {
super(props);
this.state = {
selectedRowKeys: [],
};
}
onSelectAllChange = (selected, selectedRows) => {
const keys = selected ? selectedRows.map(row => row.key) : [];
this.setState({ selectedRowKeys: keys });
};
render() {
const { selectedRowKeys } = this.state;
const dataSource = /* your data source */;
const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
// Handle row selection changes if needed
this.setState({ selectedRowKeys });
},
};
return (
<div>
<Checkbox
indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < dataSource.length}
checked={selectedRowKeys.length === dataSource.length}
onChange={(e) => this.onSelectAllChange(e.target.checked, dataSource)}
>
全选
</Checkbox>
<Table
rowSelection={rowSelection}
dataSource={dataSource}
columns={/* your columns */}
/>
</div>
);
}
}
export default YourComponent;
在这个例子中,我们使用了类组件的状态来管理选中的行,并在 onSelectAllChange 方法中更新状态。然后,将状态传递给表格的 rowSelection 属性,以确保表格中的行能够反映全选状态。