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

如何为Material UI DataGrid的内置复选框绑定点击事件?

解决方案

方案1:直接使用onSelectionModelChange回调(推荐,无需修改现有配置)

你已经配置了disableSelectionOnClick属性,此时行点击不会触发选中状态变更,onSelectionModelChange回调的唯一触发来源就是用户点击复选框(包含表头全选复选框),直接在该回调内添加你的业务逻辑即可:

<DataGrid
  checkboxSelection
  columnBuffer={0}
  disableColumnMenu
  disableColumnSelector
  disableDensitySelector
  disableSelectionOnClick
  hideFooterPagination
  hideFooter
  rows={rows}
  columns={columns}
  onCellEditCommit={params => handleUpdate(params)}
  selectionModel={selectionModel}
  onSelectionModelChange={(model: GridSelectionModel) => {
    setSelectionModel(model)
    // 此处添加复选框点击后的业务逻辑,model为当前所有选中行的id数组
    console.log('当前选中行ID列表', model)
  }}
/>

方案2:自定义复选框列(适合需要区分点击来源的场景)

如果需要区分用户点击的是表头全选复选框还是单行复选框,可以关闭默认的checkboxSelection属性,手动定义复选框列,自行绑定点击事件:

  1. 首先修改列配置,新增自定义复选框列:
const columns = [
  {
    field: 'selectionCheckbox',
    headerName: '',
    width: 50,
    sortable: false,
    filterable: false,
    disableColumnMenu: true,
    // 渲染表头全选复选框
    renderHeader: () => (
      <Checkbox
        checked={selectionModel.length === rows.length && rows.length > 0}
        indeterminate={selectionModel.length > 0 && selectionModel.length < rows.length}
        onClick={(e) => {
          // 全选复选框点击逻辑
          const newSelection = selectionModel.length === rows.length 
            ? [] 
            : rows.map(row => row.id)
          setSelectionModel(newSelection)
          console.log('表头全选复选框被点击')
        }}
      />
    ),
    // 渲染单行复选框
    renderCell: (params) => (
      <Checkbox
        checked={selectionModel.includes(params.id)}
        onClick={(e) => {
          e.stopPropagation()
          // 单行复选框点击逻辑
          const newSelection = selectionModel.includes(params.id)
            ? selectionModel.filter(id => id !== params.id)
            : [...selectionModel, params.id]
          setSelectionModel(newSelection)
          console.log(`行ID为${params.id}的复选框被点击`)
        }}
      />
    )
  },
  // 保留你原有的其他列配置
  // ...
]
  1. 移除DataGrid组件的checkboxSelection属性即可。

内容的提问来源于stack exchange,提问作者J. Jackson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:24:03