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

如何区分MUI X Data Grid中行点击与复选框点击操作?

解决MUI X Data Grid中复选框点击触发onCellClick的问题

要实现复选框多选行,同时仅在点击非复选框单元格时执行打开模态框等操作,核心是在onCellClick事件中排除复选框列的触发逻辑,具体实现如下:

关键思路

MUI X Data Grid的内置复选框列对应的字段固定为__check__,我们可以通过判断点击单元格所属列的field是否等于该值,来决定是否执行后续操作。

代码示例

import { DataGrid } from '@mui/x-data-grid';

const columns = [
  { field: 'name', headerName: '名称', width: 150 },
  { field: 'age', headerName: '年龄', width: 100 },
];

const rows = [
  { id: 1, name: '张三', age: 25 },
  { id: 2, name: '李四', age: 30 },
];

const MyDataGrid = () => {
  const handleOpenModal = (row) => {
    // 这里是打开模态框的逻辑,比如通过useState控制模态框显示
    console.log('打开模态框,行数据:', row);
  };

  const handleCellClick = (params) => {
    // 排除复选框列的点击事件
    if (params.colDef.field !== '__check__') {
      handleOpenModal(params.row);
    }
  };

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        checkboxSelection // 启用复选框多选
        onCellClick={handleCellClick}
      />
    </div>
  );
};

export default MyDataGrid;

补充说明

如果你自定义了复选框列(而非使用默认的checkboxSelection配置),只需要将判断条件中的__check__替换为你自定义列的field值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:32:07