【问题标题】:How to enable checkboxs in Table of Ant Design by conditional?如何通过条件启用 Ant Design 表中的复选框?
【发布时间】:2021-05-26 03:53:16
【问题描述】:

我想在选定行时禁用未选定行> 3。我做到了,但我不知道如何在选定行selected.length < 3 但它不起作用。

这是我的代码:https://codesandbox.io/s/selection-ant-design-demo-forked-4s6uo?file=/index.js

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    行选择不需要额外的状态。 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}
        />
      );
    };
    

    工作沙盒

    Disabling Rows

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2019-10-22
      • 2022-11-22
      • 2012-11-10
      • 2021-06-14
      • 2018-11-29
      相关资源
      最近更新 更多