You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何仅渲染一次表格子表头?

解决React表格子表头重复渲染问题

问题分析

你当前的代码会为每个item重复渲染对应类别的子表头,原因是在map遍历每个item时,都会先渲染一次表头再渲染item行。要实现每个子表头仅显示一次,需要先将items按类别分组,再按组渲染表头和对应行。

解决方案代码

首先,使用reduce将items按category分组:

// 按类别分组items
const groupedItems = items.reduce((acc, component) => {
  const { category } = component;
  if (!acc[category]) {
    acc[category] = [];
  }
  acc[category].push(component);
  return acc;
}, {});

// 类别名称映射(可选,让代码更易维护)
const categoryDisplayNames = {
  libraries: 'Libraries',
  softwareComponents: 'Software Components'
};

然后修改表格渲染逻辑,按分组后的类别渲染:

{Object.entries(groupedItems).map(([category, components]) => (
  <React.Fragment key={category}>
    {/* 仅渲染一次当前类别的子表头 */}
    <tr>
      <th>{categoryDisplayNames[category]}</th>
      <th>&nbsp;</th>
    </tr>
    {/* 渲染当前类别下的所有item行 */}
    {components.map((component) => (
      <tr key={component.name}>
        <td>{component.name}</td>
        <td>{component.version}</td>
      </tr>
    ))}
  </React.Fragment>
))}

说明

  • 通过reduce将相同类别的item归为一组,确保每个类别只处理一次。
  • 遍历分组后的类别时,先渲染一次该类别的表头,再遍历组内所有item渲染对应行,避免了表头重复。
  • 使用categoryDisplayNames映射类别键和显示名称,让代码更清晰且易于后续修改。

内容的提问来源于stack exchange,提问作者mrks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:15:39