网上的文章基本都是错的,都不能解决Ant design表格默认选中问题,网上大多数搜到的文章都是下面这种:
明明 getCheckboxProps 这个就是默认的多选框的配置,怎么 checked 或者 defaultChecked 就不行呢,而 selectedRowKeys 在这里面又不会使用。
那么 Ant Design 的表格默认选中怎么实现呢?正确的代码如下:
const LinkTable = (props) => {
const actionRef = useRef();
const {dispatch} = props;
const [selectedRowKeys,setSelectedRowKeys] = useState([]);
const [selectedRowsState,setSelectedRows] = useState([]);
const columns = [
{
title: '菜谱ID',dataIndex: 'id',},{
title: '菜谱名称',dataIndex: 'name',{
title: '一级分类',dataIndex: 'type_level1s',{
title: '二级分类',dataIndex: 'type_level2s',];
return (
<PageContainer>
<ProTable
actionRef={actionRef}
rowKey="id"
search={{
labelWidth: 120,}}
request={(params,sorter,filter) =>
queryRecipeLink({...params,filter})
}
columns={columns}
rowSelection={{
type: 'checkbox',selectedRowKeys: selectedRowKeys,onChange: (selectedRowKeys,selectedRows) => {
setSelectedRowKeys(selectedRowKeys)
console.log(`selectedRowKeys1: ${selectedRowKeys}`,'selectedRows1: ',selectedRows);
},}}
/>
{selectedRowsState?.length > 0 && (
<FooterToolbar
extra={
<div>
已选择{' '}
<a
style={{
fontWeight: 600,}}
>
{selectedRowsState.length}
</a>{' '}
项
</div>
}
>
<Button type="primary">
<Popconfirm
title={`确定关联列表选中的${selectedRowsState.length}个菜谱吗?`}
okText="确定"
cancelText="取消"
onConfirm={() => {
handleRelative(selectedRowsState).then(() => {
setSelectedRows([]);
actionRef.current?.reloadAndRest();
});
}}
>
<a>批量关联</a>
</Popconfirm>
</Button>
</FooterToolbar>
)}
</PageContainer>
);
};
export default connect(({}) => ({}))(LinkTable);
主要关注 ProTable 标签下 rowSelection 属性就可以了,selectedRowKeys 存放我们需要选中的行的 id,图示如下:
到此我们就完成了 React Ant Design 的表格初始默认选中了。