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

如何在MUI DataGrid外部使用useGridApiContext

在MUI DataGrid组件外部使用useGridApiContext的方法

要在DataGrid组件外部调用其API(比如展开所有树形行),不需要依赖自定义工具栏,有两种实用方案:

方案一:直接使用apiRef获取Grid实例

通过创建apiRef并传递给DataGridPro,就能在组件外部直接调用Grid的API方法:

import { useGridApiRef, DataGridPro } from '@mui/x-data-grid-pro';

function YourComponent() {
  // 创建Grid API引用
  const apiRef = useGridApiRef();

  // 定义展开所有行的方法
  const expandAllRows = () => {
    apiRef.current?.expandAllRows();
  };

  return (
    <>
      {/* 外部按钮,点击触发展开 */}
      <button onClick={expandAllRows}>展开所有行</button>
      <DataGridPro
        apiRef={apiRef} // 将apiRef传递给DataGridPro
        rows={works}
        columns={columns}
        treeData
        getTreeDataPath={(row) => row.hierarchy}
        groupingColDef={{
          headerName: "grtgx",
          resizable: true,
          flex: 1,
          renderCell: (props) => <CustomGroupingRow props={props} />,
        }}
        components={{
          Footer: CustomFooter,
          Toolbar: CustomToolbar,
        }}
      />
    </>
  );
}

方案二:用GridApiProvider共享API上下文

如果外部按钮是独立组件或层级较深,可以用GridApiProvider将DataGrid和外部组件包裹起来,这样外部组件就能通过useGridApiContext获取API引用:

import { GridApiProvider, useGridApiContext, DataGridPro } from '@mui/x-data-grid-pro';

// 独立的外部按钮组件
function ExpandAllButton() {
  // 通过上下文获取Grid API引用
  const apiRef = useGridApiContext();

  const handleExpandAll = () => {
    apiRef?.expandAllRows();
  };

  return <button onClick={handleExpandAll}>展开所有行</button>;
}

function YourComponent() {
  const apiRef = useGridApiRef();

  return (
    {/* 用GridApiProvider包裹需要共享API的组件 */}
    <GridApiProvider apiRef={apiRef}>
      <ExpandAllButton />
      <DataGridPro
        apiRef={apiRef}
        rows={works}
        columns={columns}
        treeData
        getTreeDataPath={(row) => row.hierarchy}
        groupingColDef={{
          headerName: "grtgx",
          resizable: true,
          flex: 1,
          renderCell: (props) => <CustomGroupingRow props={props} />,
        }}
        components={{
          Footer: CustomFooter,
          Toolbar: CustomToolbar,
        }}
      />
    </GridApiProvider>
  );
}

方案对比

  • 方案一适合简单场景,代码更简洁,直接通过apiRef调用方法;
  • 方案二更适合复杂组件结构,避免逐层传递apiRef,让API引用在上下文里共享。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:02:59