AgGrid如何实现两行表头且支持每行独立设置样式
AgGrid 两行表头独立样式设置方案
核心实现有两种可选方案,可根据你现有代码的改造量选择:
方案一:自定义表头渲染组件(可控性最高,推荐)
- 提前在列定义中扩展
unit字段存储单位信息,自定义表头组件拆分两行渲染,分别绑定类名即可独立设置样式
代码示例(React为例,其他框架逻辑一致)
// 自定义表头组件 const CustomHeader = (props) => { return ( <div className="ag-custom-header"> <div className="header-field">{props.colDef.headerName}</div> <div className="header-unit">{props.colDef.unit}</div> </div> ) } // 列定义配置 const columnDefs = [ { field: 'price', headerName: '单价', unit: '元/吨', headerComponent: CustomHeader, headerHeight: 56 // 固定表头高度适配两行内容 }, // 其余列配置 ]
配套CSS样式
.ag-custom-header { height: 100%; display: flex; flex-direction: column; justify-content: center; padding: 0 8px; } /* 第一行字段名样式 */ .header-field { font-size: 14px; font-weight: 600; color: #222; line-height: 1.5; } /* 第二行单位样式 */ .header-unit { font-size: 12px; color: #666; line-height: 1.4; }
方案二:基于现有自动换行实现零改造
如果已经通过拼接换行符\n实现了两行表头,不需要修改组件逻辑,直接用::first-line伪类适配样式即可:
.ag-header-cell-label .ag-header-cell-text { white-space: pre-wrap; /* 保留换行符生效 */ font-size: 12px; /* 先设置第二行单位的默认样式 */ line-height: 1.8; } /* 单独匹配第一行设置字段名样式 */ .ag-header-cell-label .ag-header-cell-text::first-line { font-size: 14px; font-weight: 600; color: #222; }
内容的提问来源于stack exchange,提问作者TDo
相关产品推荐
相关产品推荐

