复选框上的多行选择和单击 MUI DataGrid 中的行的单选
Multiple row selection on checkbox and single selection on clicking the row in MUI DataGrid
我正在使用 MUI DataGrid
version 4 组件。
我想要的是:
- 从数据网格中的复选框启用多个 selection(如果用户 select 多行使用复选框)
- 禁用数据网格行中的多个 select 离子(如果用户 select 有多行)
- 从数据网格中的行启用单个 selection(如果用户在 select 一行之后 select 另一行)。
但我得到的是:
- 复选框中的多个 select 离子已启用(我想要的)
- 行中的多个 select 离子已启用(我不想要的)。
对于行 selection,我只想要单个 selection 就像这个答案 但启用了复选框中的多个 selection。
这是我的代码:https://codesandbox.io/s/material-ui-data-grid-selection-vq1ny
这是 documentation for the selection on the Data Grid 组件。
注意:使用DataGridPro
组件是可以的。
如果问题不清楚,请告诉我。
您可以控制 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>
);
相关回答
我正在使用 MUI DataGrid
version 4 组件。
我想要的是:
- 从数据网格中的复选框启用多个 selection(如果用户 select 多行使用复选框)
- 禁用数据网格行中的多个 select 离子(如果用户 select 有多行)
- 从数据网格中的行启用单个 selection(如果用户在 select 一行之后 select 另一行)。
但我得到的是:
- 复选框中的多个 select 离子已启用(我想要的)
- 行中的多个 select 离子已启用(我不想要的)。
对于行 selection,我只想要单个 selection 就像这个答案
这是我的代码:https://codesandbox.io/s/material-ui-data-grid-selection-vq1ny
这是 documentation for the selection on the Data Grid 组件。
注意:使用DataGridPro
组件是可以的。
如果问题不清楚,请告诉我。
您可以控制 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>
);