MUI X Data Grid升级至7.2.0后单元格垂直对齐失效求助
问题原因
@mui/x-data-grid从v5升级到v7时,单元格容器的默认布局逻辑做了调整。v5版本里,单元格默认是flex布局且自带align-items: center,自定义renderCell返回的内容会自动垂直居中;但v7移除了这个默认样式,导致自定义组件只能顶部对齐。
修复方法
有三种简单方式可以恢复原有垂直居中效果:
1. 给自定义组件添加居中样式
直接在Typography的sx属性里设置占满单元格高度并垂直居中:
const cell = (props: GridRenderCellParams<any, string>): JSX.Element => ( <Typography sx={{ ...isGood, height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }} key={props.value} > {props.value} </Typography> );
2. 修改单元格容器的样式
通过renderCell参数里的sx属性,给单元格容器添加垂直居中样式:
const cell = (props: GridRenderCellParams<any, string>): JSX.Element => { props.sx = { ...props.sx, display: 'flex', alignItems: 'center' }; return ( <Typography sx={isGood} key={props.value}> {props.value} </Typography> ); };
3. 全局配置所有单元格
如果需要所有自定义renderCell的列都保持居中,可以在DataGrid上全局设置:
<DataGrid hideFooter disableRowSelectionOnClick disableColumnSelector autoHeight columnHeaderHeight={40} rows={rows} columns={columns} rowHeight={85} componentsProps={{ cell: { sx: { display: 'flex', alignItems: 'center', }, }, }} />
内容的提问来源于stack exchange,提问作者LA.27
相关产品推荐
相关产品推荐

