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

如何在MUI X DataGrid中通过代码程序化选中/取消选中行

如何在Material UI X DataGrid中自动控制行选中状态

要实现脱离鼠标/键盘操作、基于条件自动选中/取消选中行,核心是将DataGrid的行选中状态改为受控模式,通过selectionModel和onSelectionModelChange两个属性手动管理选中行的ID集合,以此实现按钮点击、数据变化、事件触发等场景下的自动控制。


1. 基础改造:将选中状态改为受控

首先在组件中添加状态维护选中行ID,再绑定到DataGrid组件上:

function DataGridDemo() {
  const { data, isLoading, error, refetch } = useQuery('docs', Docs.getAll);
  const columns = useColumns();
  const [rows, setRows] = React.useState([]);
  // 新增:维护选中行的ID集合
  const [selectionModel, setSelectionModel] = React.useState([]);

  useEffect(() => {
    data && setRows(data);
  }, [data]);

  return (
    <Box>
      <DataGrid
        disableRowSelectionOnClick
        checkboxSelection 
        loading={isLoading || rows?.length === 0 }
        rows={rows}
        columns={columns}
        // 绑定受控选中状态
        selectionModel={selectionModel}
        onSelectionModelChange={(newSelection) => setSelectionModel(newSelection)}
      />
    </Box>
  );
}

export default DataGridDemo;

2. 常见场景实现示例

场景1:点击自定义按钮选中指定行

添加按钮,点击后直接设置选中行的ID集合:

<Button 
  variant="contained" 
  onClick={() => setSelectionModel(['1', '3'])} // ID需与行数据的id字段类型匹配(字符串/数字)
  style={{ marginBottom: 16 }}
>
  选中ID为1、3的行
</Button>

场景2:数据加载完成后自动选中符合条件的行

在数据更新时,自动筛选并选中满足条件的行:

useEffect(() => {
  if (data) {
    setRows(data);
    // 示例:选中所有状态为"已完成"的行(根据你的数据字段调整)
    const targetRowIds = data.filter(row => row.status === '已完成').map(row => row.id);
    setSelectionModel(targetRowIds);
  }
}, [data]);

场景3:通过其他组件状态变化触发选中

比如联动下拉框,选择分类后自动选中对应分类的所有行:

const [selectedCategory, setSelectedCategory] = React.useState('');

// 分类变化时更新选中行
useEffect(() => {
  if (!rows.length) return;
  const categoryRowIds = rows.filter(row => row.category === selectedCategory).map(row => row.id);
  setSelectionModel(categoryRowIds);
}, [selectedCategory, rows]);

// 下拉框组件
<Select
  value={selectedCategory}
  onChange={(e) => setSelectedCategory(e.target.value)}
  style={{ marginBottom: 16 }}
>
  <MenuItem value="前端">前端</MenuItem>
  <MenuItem value="后端">后端</MenuItem>
</Select>

注意事项

  • selectionModel中的ID必须与行数据的id字段类型完全一致(字符串/数字),否则选中状态不生效。
  • 取消所有选中只需调用setSelectionModel([])。
  • 数据更新(如调用refetch)时,需同步更新选中状态,避免数据与选中状态不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:42:45