【发布时间】:2021-05-26 03:53:16
【问题描述】:
我想在选定行时禁用未选定行> 3。我做到了,但我不知道如何在选定行selected.length < 3 但它不起作用。
这是我的代码:https://codesandbox.io/s/selection-ant-design-demo-forked-4s6uo?file=/index.js
【问题讨论】:
我想在选定行时禁用未选定行> 3。我做到了,但我不知道如何在选定行selected.length < 3 但它不起作用。
这是我的代码:https://codesandbox.io/s/selection-ant-design-demo-forked-4s6uo?file=/index.js
【问题讨论】:
行选择不需要额外的状态。 rowSelection 的 onChange 属性为您提供选定的行。我们只需要映射它来获取行键。
onChange: (selectedRowKeys, selectedRows) => {
setSelected(selectedRows.map(row => row.key))
},
一旦你有了行键,现在我们需要做的就是检查行键是否不是所选键的一部分。如果选定的行大于 2 并且该行的键不在选定的键中,那么我们将禁用它。
getCheckboxProps: (record) => {
if (selected.length > 2) {
return {
disabled: !selected.includes(record.key)
};
}
}
完整代码
const Demo = () => {
const [selected, setSelected] = useState([]);
return (
<Table
rowSelection={{
onChange: (selectedRowKeys, selectedRows) => {
setSelected(selectedRows.map(row => row.key))
},
getCheckboxProps: (record) => {
if (selected.length > 2) {
return {
disabled: !selected.includes(record.key)
};
}
}
}}
columns={columns}
dataSource={data}
/>
);
};
工作沙盒
【讨论】: