MUI DataGrid Pro 6.18.2列分组实现求助(无需付费升级)
实现MUI DataGrid Pro 6.18.2列分组效果的替代方案
方法一:CSS Hack模拟列头分组
针对你的版本,可通过自定义CSS模拟列头分组的视觉效果,核心是给指定列的表头预留空间并添加分组标题。
步骤:
- 给需要归为同一组的列添加自定义类名:
const columns = [ { field: 'group1_col1', headerName: '子列1', headerClassName: 'group1-col' }, { field: 'group1_col2', headerName: '子列2', headerClassName: 'group1-col' }, { field: 'group2_col1', headerName: '子列A', headerClassName: 'group2-col' }, { field: 'group2_col2', headerName: '子列B', headerClassName: 'group2-col' }, ];
- 添加全局CSS样式生成分组标题:
/* 调整表头高度,容纳分组标题 */ .MuiDataGrid-columnHeaders { height: 64px !important; } /* 分组1样式 */ .group1-col .MuiDataGrid-columnHeaderTitle { padding-top: 24px; } .group1-col:first-of-type::before { content: "分组1"; position: absolute; top: 0; left: 0; right: 0; height: 24px; line-height: 24px; text-align: center; background-color: #f5f5f5; border-bottom: 1px solid #e0e0e0; font-weight: 600; } /* 分组2样式 */ .group2-col .MuiDataGrid-columnHeaderTitle { padding-top: 24px; } .group2-col:first-of-type::before { content: "分组2"; position: absolute; top: 0; left: 0; right: 0; height: 24px; line-height: 24px; text-align: center; background-color: #f5f5f5; border-bottom: 1px solid #e0e0e0; font-weight: 600; }
注意:
- 仅为视觉模拟,不支持分组折叠、拖拽调整分组等交互
- 若列需拖拽排序,需额外调整CSS定位逻辑
方法二:自定义列头组件实现分组
如果需要更灵活的控制,可通过renderHeader属性自定义列头组件,手动构建分组结构。
示例代码:
// 自定义分组标题组件 const GroupHeader = ({ groupName }) => ( <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 24, backgroundColor: '#f5f5f5', borderBottom: '1px solid #e0e0e0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, }}> {groupName} </div> ); // 列配置 const columns = [ { field: 'group1_col1', headerName: '子列1', renderHeader: () => ( <div style={{ position: 'relative', paddingTop: 24 }}> <GroupHeader groupName="分组1" /> 子列1 </div> ), }, { field: 'group1_col2', headerName: '子列2', renderHeader: () => ( <div style={{ position: 'relative', paddingTop: 24 }}>子列2</div> ), }, { field: 'group2_col1', headerName: '子列A', renderHeader: () => ( <div style={{ position: 'relative', paddingTop: 24 }}> <GroupHeader groupName="分组2" /> 子列A </div> ), }, { field: 'group2_col2', headerName: '子列B', renderHeader: () => ( <div style={{ position: 'relative', paddingTop: 24 }}>子列B</div> ), }, ]; // 调整表头高度 const useStyles = makeStyles({ columnHeaders: { height: 64, }, }); // 组件使用 const MyDataGrid = () => { const classes = useStyles(); return ( <DataGridPro rows={tableData} columns={columns} getRowId={(row) => row.id} classes={{ columnHeaders: classes.columnHeaders }} /> ); };
优势:
- 可自定义分组标题的样式、交互(如添加点击事件)
- 比CSS hack更灵活,适配不同列宽场景
总结
两种方法均为视觉模拟付费版列分组效果,无法实现付费版的完整交互(如分组折叠、自动列宽适配等),但能满足基础展示需求,可根据产品场景选择合适方案。
内容的提问来源于stack exchange,提问作者Shalabh Goel
相关产品推荐
相关产品推荐

