【问题标题】:Multiple row selection on checkbox and single selection on clicking the row in MUI DataGrid复选框上的多行选择和单击 MUI DataGrid 中的行时的单选
【发布时间】:2021-12-16 00:07:22
【问题描述】:

我正在使用MUI DataGrid version 4 组件。

我想要的是:

  1. 从数据网格中的复选框启用多项选择(如果用户使用复选框选择多行)
  2. 禁用数据网格中行的多项选择(如果用户选择了多行)
  3. 启用从数据网格中的行进行单选(如果用户在选择一行后选择另一行)。

但我得到的是:

  1. 复选框中的多项选择已启用(我想要什么
  2. 已启用该行的多项选择(我不想要的)。

对于行选择,我只想要一个像这个答案MUI - Disable multiple row selection in DataGrid 这样的单一选择,但启用了复选框中的多个选择。

这是我的代码:https://codesandbox.io/s/material-ui-data-grid-selection-vq1ny

这是documentation for the selection on the Data Grid 组件。

注意:可以使用DataGridPro 组件。

如果问题不清楚,请告诉我。

【问题讨论】:

  • 2.和 3. 是一回事吗?
  • 是的,你是对的

标签: javascript reactjs typescript datagrid material-ui


【解决方案1】:

您可以控制selectionModel 状态并检查用户是否单击了单元格(而不是复选框)。如果他们点击复选框,onCellClick 将不会被触发,如果他们点击其他单元格,onCellClick 将被触发,然后根据该信息相应地更新selectionModel

const cellClickRef = React.useRef(null);
const [selectionModel, setSelectionModel] = React.useState([]);

return (
  <div style={{ height: 400, width: '100%' }}>
    <DataGrid
      checkboxSelection
      selectionModel={selectionModel}
      onCellClick={() => (cellClickRef.current = true)}
      onSelectionModelChange={(selection, detail) => {
        if (cellClickRef.current) {
          if (selection.length > 1) {
            const selectionSet = new Set(selectionModel);
            const result = selection.filter((s) => !selectionSet.has(s));

            setSelectionModel(result);
          } else {
            setSelectionModel(selection);
          }
        } else {
          setSelectionModel(selection);
        }
        cellClickRef.current = null;
      }}
      {...data}
    />
  </div>
);

相关答案

【讨论】:

  • 哇很好的解释和答案。我什至不考虑onCellClick 道具。我想知道你为什么使用cellClickRef.current = true 而不是setCellClickRef(cellClickRef.current)
  • @JabalLogian 我使用useRef 而不是useState 来防止额外的重新渲染。每次调用 setState 时,组件都会再次呈现,在这种情况下这是不必要的。当您单击一个单元格以选择一行时,无论组件是否呈现,都会调用onCellClick 然后onSelectionModelChange 回调
猜你喜欢
  • 2019-11-29
  • 2022-06-14
  • 2021-05-31
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2021-06-23
相关资源
最近更新 更多