【问题标题】:Material-UI Data-Grid: How pass parameter to custom toolbar?Material-UI Data-Grid:如何将参数传递给自定义工具栏?
【发布时间】:2026-01-16 01:00:01
【问题描述】:

我在 datagrid (Material-UI) 中定义了一个自定义工具栏(参见:https://material-ui.com/components/data-grid/rendering/#toolbar) 我从这个例子开始:https://codesandbox.io/s/x58yv?file=/demo.js

我想显示或隐藏带有过渡的工具栏。 由于我们无法将自定义道具传递给组件:

   <DataGrid
    ...
    components={{ Toolbar: CustomToolbar }}
    ...
   </DataGrid>

所以我使用了这样的上下文 API:

   export function CustomToolbar(props: GridBaseComponentProps) {
    const classes = useToolbarStyles();
    const toolbarContext = useContext(ToolbarContext);
    return (
        <Collapse in={toolbarContext.toolbar}>
            <GridToolbarContainer className={classes.root}>
                <GridColumnsToolbarButton />
                <GridFilterToolbarButton />
                <GridDensitySelector />
                <GridToolbarExport />
            </GridToolbarContainer>
        </Collapse>
    );
   }

它有效,但有更好的解决方案吗?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您应该能够使用 DataGrid 的 componentsProps 属性来传递任何其他属性(请参阅https://material-ui.com/api/data-grid/),例如

    <DataGrid
        ...
        components={{ Toolbar: CustomToolbar }}
        componentsProps={{ toolbar: { myCustomProp: 8 } }}
        ...
    </DataGrid>
    

    【讨论】:

    • 非常感谢完美和快速的回​​答 :) 笑脸!
    • 警告:material-ui 的类型不检查道具类型,因此您需要自己强制执行类型。