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

如何获取MUI Data Grid中当前获得焦点的单元格ID?

获取MUI Data Grid当前焦点单元格的方法

完全可以实现,下面分两种常用场景说明具体做法:

1. 实时监听焦点单元格变化

通过cellFocusChange事件可以实时捕获焦点单元格的切换——不管是鼠标点击、键盘箭头导航还是手动设置焦点,都会触发这个事件。

在函数组件中可以用useGridEventListener钩子来监听:

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

// 封装可复用的监听组件
function GridFocusMonitor() {
  const gridApi = useGridApiContext();

  useGridEventListener(gridApi, 'cellFocusChange', (params) => {
    // params.focusedCell 包含当前焦点单元格的rowId和field
    console.log('当前焦点单元格:', params.focusedCell);
    // 可根据需求做后续处理,比如更新状态、高亮单元格等
  });

  return null;
}

// 在DataGrid页面中使用
function MyDataGrid() {
  const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'name', headerName: '姓名', width: 130 },
    { field: 'age', headerName: '年龄', width: 90 },
  ];
  const rows = [
    { id: 1, name: '张三', age: 25 },
    { id: 2, name: '李四', age: 30 },
  ];

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} />
      <GridFocusMonitor />
    </div>
  );
}

2. 任意时刻主动获取当前焦点单元格

如果需要在特定时机(比如点击按钮、执行自定义操作时)获取当前焦点单元格,可以通过Grid API的getFocusedCell方法直接获取。

示例代码:

import { DataGrid, useGridApiRef } from '@mui/x-data-grid';
import Button from '@mui/material/Button';

function MyDataGrid() {
  const columns = [/* 你的列定义 */];
  const rows = [/* 你的行数据 */];
  const apiRef = useGridApiRef();

  const checkFocusedCell = () => {
    const focusedCell = apiRef.current.getFocusedCell();
    if (focusedCell) {
      console.log('当前焦点单元格信息:', focusedCell);
      // 可进一步获取单元格数据:apiRef.current.getRow(focusedCell.rowId)[focusedCell.field]
    } else {
      console.log('当前没有焦点单元格');
    }
  };

  return (
    <div>
      <Button variant="contained" onClick={checkFocusedCell}>查看当前焦点单元格</Button>
      <div style={{ height: 400, width: '100%', marginTop: 16 }}>
        <DataGrid rows={rows} columns={columns} apiRef={apiRef} />
      </div>
    </div>
  );
}

补充说明

  • getFocusedCell方法返回的对象结构为{ rowId: number | string, field: string },无焦点时返回null。
  • 如果使用类组件,可通过ref获取Grid实例后,调用ref.current.api.getFocusedCell()实现同样功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:05:02