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

如何在Material UI的DataGrid外部修改行选中状态

问题:选中项关闭操作无法同步到DataGrid

我希望展示选中行的名称,并且点击选中元素的关闭按钮时,该操作能同步反映到DataGrid中。目前的问题是,顶部选中的蛋糕中移除Designer Cake后,DataGrid里的选中状态没跟着变。

解决方法

问题根源是你只维护了选中名称的数组,但DataGrid的选中状态依赖行ID集合控制,所以需要同时维护选中ID的状态,而非仅存名称。

具体步骤

  • 将状态从selectedRows(存储名称)改为selectedRowIds(存储行ID),直接和DataGrid的选中模型对应
  • 渲染顶部选中标签时,通过ID匹配对应的行名称
  • 点击关闭按钮时移除对应ID,同步更新DataGrid的选中状态
  • DataGrid的onSelectionModelChange直接更新selectedRowIds,再通过ID映射出要展示的名称

修改后的完整代码

import { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import GrClose from 'react-icons/gr';

// 假设columns是你已定义的列配置
const columns = [/* 你的列配置 */];

export default function CakeGrid() {
  const [rows, setRows] = useState([]);
  // 维护选中的行ID集合,替代原有的selectedRows
  const [selectedRowIds, setSelectedRowIds] = useState([]);

  // 根据选中ID获取对应的蛋糕名称数组,用于顶部标签渲染
  const selectedCakeNames = rows
    .filter(row => selectedRowIds.includes(row._id.toString()))
    .map(row => row.name);

  return (
    <div className="min-vh-100 min-vw-100 d-flex flex-column">
      <div className="m-4">
        Selected Cakes:
        {selectedCakeNames.map((name) => {
          // 找到当前名称对应的行ID
          const targetRowId = rows.find(row => row.name === name)?._id.toString();
          return (
            <span key={targetRowId} className="m-2 bg-success border border-2 px-2 py-1 rounded-pill border-bg-primary">
              <span className="text-white">{name}</span>
              <GrClose
                color="white"
                size="1rem"
                className="ms-2 cursor-pointer"
                onClick={() => {
                  // 移除对应ID,同步更新DataGrid选中状态
                  setSelectedRowIds(prevIds => prevIds.filter(id => id !== targetRowId));
                }}
              />
            </span>
          );
        })}
      </div>
      <div className="flex-grow-1">
        <DataGrid
          className="min-vh-100"
          getRowId={(row) => row._id}
          rows={rows}
          columns={columns}
          pageSize={30}
          rowsPerPageOptions={[30]}
          checkboxSelection
          disableSelectionOnClick
          experimentalFeatures={{ newEditingApi: true }}
          autoHeight={true}
          autoPageSize={true}
          // 绑定选中模型到selectedRowIds,实现双向同步
          selectionModel={selectedRowIds}
          onSelectionModelChange={(newSelectedIds) => {
            setSelectedRowIds(newSelectedIds);
          }}
        />
      </div>
    </div>
  );
}

关键说明

  • 核心逻辑:selectedRowIds直接绑定DataGrid的selectionModel,确保选中状态的双向同步
  • 关闭按钮操作:点击时移除对应ID,DataGrid会自动根据selectionModel更新选中状态
  • 数据一致性:通过ID从原始rows中映射名称,避免维护重复的名称数据,保证数据统一

内容的提问来源于stack exchange,提问作者krishnaacharyaa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:20:14