如何实现表格左侧表头单元格跨多行显示?
解决左侧表头跨多行显示的问题
你现在的问题是每个数据行都重复渲染了左侧表头,没实现单元格跨行合并。核心问题在于没对同属一个label的数据分组,也没用到表格的rowspan属性来实现跨行效果。
修复思路
- 按label分组数据:把相同
rowLabel的数据归为一组,方便计算每组行数来设置跨行 - 利用
rowspan属性:每组第一行渲染label单元格,并设置rowspan为该组的行数,后续行不再渲染label单元格 - 恢复表格默认布局:原来的
flex布局会破坏表格的单元格合并逻辑,改用表格自带的布局规则
修改后的代码
// 先对data按rowLabel分组 const groupedData = data.reduce((acc, row) => { if (!acc[row.rowLabel]) { acc[row.rowLabel] = []; } acc[row.rowLabel].push(row); return acc; }, {}); // 渲染分组后的数据 return ( <table style={{ borderCollapse: 'collapse', width: '100%' }}> {Object.entries(groupedData).map(([label, rows], groupIndex) => ( <> {rows.map((row, rowIndex) => ( <tr key={`${groupIndex}-${rowIndex}`} style={{ borderBottom: '1px solid #E1D9D6' }}> {/* 仅每组第一行渲染label,并设置跨行数 */} {rowIndex === 0 && ( <td style={{ width: '33%', textAlign: 'center', borderRight: '1px solid #E1D9D6', fontSize: '9px', verticalAlign: 'middle', }} rowSpan={rows.length} > {label} </td> )} <td style={{ width: '33%', paddingLeft: '5px', fontSize: '9px' }}> {row.key} </td> <td style={{ borderLeft: '1px solid #E1D9D6', width: '34%', textAlign: 'right', fontSize: '9px', paddingRight: '5px', }} > {row.value} </td> </tr> ))} </> ))} </table> );
关键说明
- 分组逻辑:用
reduce把数据转换成{ 标签名: [对应数据行] }的结构,能直接获取每个标签下的行数 rowspan作用:设置rowSpan={rows.length}后,该单元格会跨占对应行数的高度,实现表头跨行显示- 表格样式:
borderCollapse: 'collapse'让表格边框合并,移除flex后表格能正常解析单元格跨行规则
这样修改后就能实现你预期的左侧表头跨多行效果了。
内容的提问来源于stack exchange,提问作者julcodecode
相关产品推荐
相关产品推荐

