如何自定义MUI X Data Grid工具栏仅显示图标
移除MUI X Data Grid工具栏按钮文本,仅保留图标
你可以通过以下几种方式实现需求:
方法一:直接给工具栏按钮组件添加showLabel属性
修改自定义工具栏组件,给每个按钮设置showLabel={false},即可隐藏文本只显示图标:
function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton showLabel={false} /> <GridToolbarFilterButton showLabel={false} /> <GridToolbarDensitySelector showLabel={false} /> <GridToolbarExport showLabel={false} /> </GridToolbarContainer> ); } <DataGrid {...data} slots={{ toolbar: CustomToolbar, }} />
方法二:通过slotProps统一配置(无需修改CustomToolbar)
如果不想改动自定义工具栏组件,可以在DataGrid的slotProps里给所有工具栏按钮统一设置属性:
<DataGrid {...data} slots={{ toolbar: CustomToolbar, }} slotProps={{ toolbar: { showLabel: false, }, }} />
该方式会自动应用到工具栏内的所有默认按钮组件,更简洁高效。
方法三:用CSS隐藏文本(兼容旧版本备用方案)
如果使用的MUI X版本不支持showLabel属性,可以通过自定义CSS隐藏按钮文本:
/* 全局样式或组件内样式 */ .MuiDataGrid-toolbarButton .MuiButton-label { display: none; }
也可以通过styled-components/Emotion针对单个组件定制:
import { styled } from '@mui/material/styles'; const StyledGridToolbarColumnsButton = styled(GridToolbarColumnsButton)` .MuiButton-label { display: none; } `; // 在CustomToolbar中替换使用 <StyledGridToolbarColumnsButton />
内容的提问来源于stack exchange,提问作者emir alp aksungur
相关产品推荐
相关产品推荐

