我正在使用 MUI DataGrid
version 4成分。
我想要的是:
但我得到的是:
对于行选择,我只想要一个选择,就像这个答案 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
成分。如果问题不清楚,请告诉我。
最佳答案
您可以控制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>
);
相关回答
关于javascript - 复选框上的多行选择和单击 MUI DataGrid 中的行时的单一选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69793889/