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

React JS中如何在map函数内仅显示一次表格表头?

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

问题:使用React和TailwindCSS以表格展示数据,用map遍历渲染时,表头随每一行重复出现,需要实现表头仅显示一次的表格格式。

问题原因

你的代码把**整个表格(包含表头)**放在了data.map()循环内部,导致每遍历一条数据就生成一个完整的表格,自然表头会重复出现。

解决方案

将表格的容器、<table>标签和<thead>表头部分移到循环外面,只在map循环中渲染<tbody>里的每一行数据。

修改后的代码:

{data && toggle ? (
  <div className="table-container">
    <div className="overflow-x-none flex items-center justify-center w-fit mx-auto border border-[#1B71E8]">
      <table className="table-fixed max-w-screen-lg border-seperate border-spacing">
        <thead>
          <tr>
            <th>name</th>
            <th>country</th>
            <th>carbon credits</th>
            <th>type</th>
            <th>vintage</th>
            <th>serial number</th>
          </tr>
        </thead>
        <tbody>
          {data.map((project, idx) => (
            <tr key={idx}>
              <td className="w-52 h-8 text-center">
                {project.project.name}
              </td>
              <td className="w-52 text-center">
                {project.project.country}
              </td>
              <td className="w-32 max-h-2 text-center">
                {project.number_of_credits}
              </td>
              <td className="w-52 text-center">
                {project.project.type}
              </td>
              <td className="w-52 text-center">
                {project.vintage}
              </td>
              <td className="w-52 text-center">
                {project.serial_number}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
)}

关键改动说明

  1. 把包含<table>的外层div和整个表格结构移出map循环,确保只生成一个表格容器和表头
  2. 仅在<tbody>内部使用data.map()遍历渲染每一行数据
  3. 给循环生成的<tr>加上key属性(这里用idx,如果数据有唯一ID建议用ID更规范),符合React列表渲染的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:20:29