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

如何在React Bootstrap Table中实现嵌套列?现有代码无法正常展示科目列

解决方法

你的问题出在表头的HTML结构错误——不能在<th>标签内部嵌套<tr>,这不符合HTML表格规范,导致科目列无法正确分成4列。正确的做法是将表头拆分为两行<tr>:

  1. 第一行:设置"Roll ID"、"Name"、"Age"的rowSpan="2"(跨两行),"Marks"表头设置colSpan="4"(跨4列)
  2. 第二行:放置四个科目的子表头(Maths、English、Science、Arts)

修正后的完整表格代码如下:

<Table
  striped
  bordered
  hover
  responsive
  bgcolor="white"
  size="lg"
  style={{ opacity: "0.8" }}
>
  <thead style={{ backgroundColor: "#198754" }} className="text-white">
    {/* 第一行:跨列/跨行的主表头 */}
    <tr>
      <th rowSpan={2}>Roll ID</th>
      <th rowSpan={2}>Name</th>
      <th colSpan={4}>Marks</th>
      <th rowSpan={2}>Age</th>
    </tr>
    {/* 第二行:科目子表头 */}
    <tr>
      <th>Maths</th>
      <th>English</th>
      <th>Science</th>
      <th>Arts</th>
    </tr>
  </thead>
  <tbody>
    {data.map((dat) => {
      return (
        <tr key={dat.rollId}>
          <td>{dat.rollId}</td>
          <td>{dat.name}</td>
          <td>{dat.marks.maths}</td>
          <td>{dat.marks.english}</td>
          <td>{dat.marks.science}</td>
          <td>{dat.marks.arts}</td>
          <td>{dat.age}</td>
        </tr>
      );
    })}
  </tbody>
</Table>

关键说明

  • 原代码把嵌套的<tr>放在<th rowSpan={2} colSpan={4}>内部,破坏了表格列结构,浏览器无法正确解析4个科目列
  • 拆分后的两行<tr>完全符合HTML表格嵌套规则,能让React Bootstrap Table正确渲染出目标合并表头效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:25:19