如何在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
相关产品推荐
相关产品推荐

