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

如何在MUI X Data Grid工具栏中添加自定义全选复选框

实现MUI X Data Grid工具栏自定义全选复选框

步骤1:为Data Grid添加引用(Ref)

要调用Data Grid的内置API控制行选中状态,需在父组件中创建并绑定ref到Data Grid组件。

步骤2:编写全选逻辑

在父组件中实现全选/取消全选的处理方法,通过ref调用Data Grid的setSelectionModelAPI设置所有行的选中状态。

步骤3:自定义工具栏组件

在自定义工具栏中添加MUI的Checkbox组件,传递全选方法并处理点击事件;若需同步复选框状态(全选/半选/未选),可通过父组件传递选中行数和总行数判断。


完整代码示例

父组件代码

import React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import NewToolbar from './NewToolbar';

class YourTableComponent extends React.Component {
  constructor(props) {
    super(props);
    this.gridRef = React.createRef();
    this.state = {
      cancelShipFlag: false,
      rowinfo: [],
      selectedCount: 0
    };
  }

  handleSelectAll = (checked) => {
    if (!this.gridRef.current) return;
    const { serialsList } = this.props;
    const allRowIds = (serialsList || []).map(row => row.id);
    this.gridRef.current.setSelectionModel(checked ? allRowIds : []);
  }

  render() {
    const { serialsList, columns } = this.props;
    const totalRows = serialsList?.length || 0;

    return (
      <DataGrid
        ref={this.gridRef}
        rows={serialsList || []}
        columns={columns}
        rowsPerPageOptions={[25, 50, 100]}
        checkboxSelection={this.state.cancelShipFlag}
        disableSelectionOnClick={false}
        components={{
          Toolbar: () => (
            <NewToolbar
              onSelectAll={this.handleSelectAll}
              selectedCount={this.state.selectedCount}
              totalRows={totalRows}
            />
          )
        }}
        onSelectionModelChange={(ids) => {
          const selectedIDs = new Set(ids);
          const selectedRows = (serialsList || []).filter(row => selectedIDs.has(row.id));
          this.setState({
            rowinfo: selectedRows,
            selectedCount: selectedRows.length
          });
        }}
      />
    );
  }
}

export default YourTableComponent;

自定义工具栏组件(NewToolbar.jsx)

import React from 'react';
import { Toolbar } from '@mui/x-data-grid';
import Checkbox from '@mui/material/Checkbox';
import Typography from '@mui/material/Typography';

const NewToolbar = ({ onSelectAll, selectedCount, totalRows }) => {
  const isAllSelected = selectedCount === totalRows && totalRows > 0;
  const isIndeterminate = selectedCount > 0 && selectedCount < totalRows;

  return (
    <Toolbar>
      <div style={{ display: 'flex', alignItems: 'center', marginRight: 16 }}>
        <Checkbox
          checked={isAllSelected}
          indeterminate={isIndeterminate}
          onChange={(e) => onSelectAll(e.target.checked)}
        />
        <Typography variant="body2" style={{ marginLeft: 8 }}>
          全选
        </Typography>
      </div>
      {/* 保留原工具栏默认内容,如导出、搜索等,按需调整 */}
      <Toolbar />
    </Toolbar>
  );
};

export default NewToolbar;

关键说明

  • 确保已安装@mui/material和@mui/x-data-grid(或pro版)依赖。
  • setSelectionModel是Data Grid核心API,用于直接设置选中行的ID数组。
  • 通过selectedCount和totalRows实现复选框状态同步,覆盖全选、半选、未选三种场景,优化用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:10:25