You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:42:46