首页 > 解决方案 > ant-design table 组件中仅选择一行

问题描述

我这里有问题。我的项目必须使用 ant design。链接在这里:https ://ant.design/components/table 我必须使用的组件是表格组件。当我点击一行时,我必须调度一个动作。我面临的问题是我必须只检查一行。结果,当我单击一行时,应取消选择前一行中的复选框。

如您在此处看到的,我尝试添加一些逻辑:

class EvaluationDataTable extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
  };

  onSelectChange = selectedRowKeys => {
    if (selectedRowKeys.length > 1) {
      const lastSelectedRowIndex = [...selectedRowKeys].pop();
      this.setState({ selectedRowKeys: lastSelectedRowIndex });
    }
    this.setState({ selectedRowKeys });
    console.log('selectedRowKeys changed: ', selectedRowKeys);
  };

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <React.Fragment>
        <div style={{ marginBottom: 16 }} />
        <Table
          rowSelection={rowSelection}
          columns={columnEvaluation}
          dataSource={result}
        />
      </React.Fragment>
    );
  }
}```

But even if the selectedRow has the last checked row the no checkbox is checked. Any ideas?

标签: javascriptarraysreactjscheckboxantd

解决方案


看起来您可以将 ant 设计表配置为使用单选按钮而不是复选框。由于单选按钮用于单选,这应该可以解决您的用例。文档表明 antd Table 组件有一个rowSelectionprop,它接受一个配置对象,定义在这里。其中一个选项是type,您可以将其设置为radiocheckbox。你想要radio。所以你想要这样的东西:

<Table rowSelection={{type:'radio'}} >...</Table>

推荐阅读