MUI DataGrid社区版v6实现仅选中当前页所有行方案咨询
在MUI DataGrid社区版(v6)实现付费版
checkboxSelectionVisibleOnly功能 MUI DataGrid付费版的checkboxSelectionVisibleOnly属性,可实现全选操作仅选中当前页可见行,同时支持跨页单独选中行并保留全局选中集合。你当前使用社区版v6,现有代码存在「选中单行时自动选中当前页所有行」的问题,以下是修正方案:
问题根源
你的代码核心逻辑错误:通过rowSelectionModel.length > rowSelection.length判断为全选操作,但单行选中也会满足这个条件,导致误触发全选当前页的逻辑。
修正后的代码
onRowSelectionModelChange={(rowSelectionModel) => { // 清空选中集合 if (rowSelectionModel.length === 0) { return setSelectedRows([]); } const { state: { rowSelection, pagination: { paginationModel: { page, pageSize }, }, }, getColumnHeaderSelectionProps } = apiRef.current; // 获取表头全选框状态,判断是否为全选操作触发 const headerSelectionProps = getColumnHeaderSelectionProps('id'); const isSelectAllTriggered = headerSelectionProps?.checked || headerSelectionProps?.indeterminate; // 用户取消选中行(单行/多行取消) if (rowSelectionModel.length < rowSelection.length) { return setSelectedRows(rowSelectionModel); } const startIndex = page * pageSize; const endIndex = startIndex + pageSize; const currentPageRows = apiRef.current.getAllRowIds().slice(startIndex, endIndex); // 初始无选中时,区分全选/单行选中 if (rowSelection.length === 0) { return setSelectedRows(isSelectAllTriggered ? currentPageRows : rowSelectionModel); } // 处理全选/反选当前页操作 if (isSelectAllTriggered) { const currentSelection = new Set(rowSelection); const isCurrentPageAllSelected = currentPageRows.every(rowId => currentSelection.has(rowId)); // 已全选则移除当前页,否则添加当前页 currentPageRows.forEach(rowId => { isCurrentPageAllSelected ? currentSelection.delete(rowId) : currentSelection.add(rowId); }); return setSelectedRows(Array.from(currentSelection)); } // 单行选中操作,直接更新集合 return setSelectedRows(rowSelectionModel); }}
关键修改说明
- 区分全选与单行操作:通过
getColumnHeaderSelectionProps获取表头全选框状态,精准判断是否为全选触发的变更,避免单行选中误触发全选逻辑。 - 全选逻辑优化:先检查当前页是否已全部选中,再执行批量添加/移除,符合用户对全选框的常规预期。
- 保留跨页选中:单行选中时直接更新全局选中集合,切换页面后选中的行不会丢失。
内容的提问来源于stack exchange,提问作者breq
相关产品推荐
相关产品推荐

