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

如何在MUI X Data Grid中通过点击实现行的选中与取消选中(无checkboxSelection)

实现@mui/x-data-grid行点击选中/取消(无需checkboxSelection)

要实现点击行切换选中状态,你可以通过维护选中行ID的状态,结合onRowClick事件来完成,具体修改如下:

步骤1:添加状态管理

在组件内部添加useState存储选中的行ID数组:

const [selectedRowIds, setSelectedRowIds] = React.useState([]);

步骤2:实现行点击处理逻辑

编写处理行点击的函数,判断当前行是否已选中,切换其选中状态:

const handleRowClick = (params) => {
  const rowId = params.id;
  setSelectedRowIds(prev => {
    if (prev.includes(rowId)) {
      // 已选中则移除
      return prev.filter(id => id !== rowId);
    } else {
      // 未选中则添加
      return [...prev, rowId];
    }
  });
};

步骤3:优化数据ID生成(避免重复渲染)

原代码每次渲染都会重新生成UUID,导致表格频繁重绘,用useMemo包裹数据处理逻辑:

const processedData = React.useMemo(() => {
  return data.map(element => ({ ...element, id: v1() }));
}, [data]);

步骤4:配置DataGrid属性

在DataGrid中添加点击事件、选中模型配置,明确关闭checkboxSelection:

<DataGrid
  className={`${css.root}`}
  rows={processedData}
  columns={tableHeader}
  pageSize={10}
  rowHeight={30}
  autoPageSize={true}
  disableColumnMenu={true}
  components={{
    Toolbar: CustomToolbar,
  }}
  checkboxSelection={false}
  rowSelectionMode="multiple"
  rowSelectionModel={selectedRowIds}
  onRowClick={handleRowClick}
/>

完整修改后的组件代码

import * as React from "react";
import { v1 } from "uuid";
import {
  DataGrid,
  GridToolbarContainer,
  GridToolbarExport
} from "@mui/x-data-grid";

//css
import css from "./index.module.css";

export default function Table(props) {
  const { tableHeader, data } = props;
  // 维护选中行ID的状态
  const [selectedRowIds, setSelectedRowIds] = React.useState([]);

  // 优化数据处理,避免每次渲染重新生成ID
  const processedData = React.useMemo(() => {
    return data.map(element => ({ ...element, id: v1() }));
  }, [data]);

  // 行点击处理函数
  const handleRowClick = (params) => {
    const rowId = params.id;
    setSelectedRowIds(prev => {
      return prev.includes(rowId)
        ? prev.filter(id => id !== rowId)
        : [...prev, rowId];
    });
  };

  function CustomToolbar() {
    return (
      <GridToolbarContainer>
        <GridToolbarExport className={`${css.btn}`} />
      </GridToolbarContainer>
    );
  }

  return (
    <div style={{ height: 350, width: "100%" }}>
      <DataGrid
        className={`${css.root}`}
        rows={processedData}
        columns={tableHeader}
        pageSize={10}
        rowHeight={30}
        autoPageSize={true}
        disableColumnMenu={true}
        components={{
          Toolbar: CustomToolbar,
        }}
        checkboxSelection={false}
        rowSelectionMode="multiple"
        rowSelectionModel={selectedRowIds}
        onRowClick={handleRowClick}
      />
    </div>
  );
}

补充说明

  • 如果需要单选模式,只需把rowSelectionMode改为"single",此时选中行会自动替换,无需手动处理去重逻辑
  • 表格会自动给选中的行添加默认选中样式,如需自定义样式,可通过rowClassName属性根据行是否选中设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:39:36