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

React Bootstrap中Table高度失效:如何实现表头固定表体滚动?

React-Bootstrap Table固定表头并实现表体滚动

要解决Table溢出容器、表头固定的问题,核心是调整table的布局规则,让thead脱离流式布局固定在顶部,tbody单独设置滚动区域。以下是修改后的实现代码:

import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  return (
    <div style={{ height: "200px", backgroundColor: "aqua", overflow: "hidden" }}>
      <Table striped bordered style={{ tableLayout: "fixed", width: "100%", margin: 0 }}>
        <thead style={{ position: "sticky", top: 0, backgroundColor: "#fff" }}>
          <tr>
            <th>#</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Username</th>
          </tr>
        </thead>
        <tbody style={{ display: "block", height: "calc(100% - 48px)", overflowY: "auto" }}>
          <tr>
            <td>1</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
          </tr>
          <tr>
            <td>3</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <td>4</td>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
          </tr>
          <tr>
            <td>5</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <td>6</td>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
          </tr>
        </tbody>
      </Table>
    </div>
  );
}

关键修改说明:

  • 外层容器添加overflow: hidden:避免容器整体出现滚动条,仅保留表体的滚动区域。
  • Table组件设置tableLayout: fixed+width: 100%:固定列宽,确保表头与表体的列对齐,防止滚动时错位。
  • thead设置position: sticky; top: 0:让表头固定在容器顶部,backgroundColor: #fff防止滚动时下方内容透显。
  • tbody设置display: block:将默认的table-row-group布局改为块级,允许设置高度和滚动;height: calc(100% - 48px):减去表头的固定高度(可根据实际样式调整数值);overflowY: auto:内容超出时自动显示垂直滚动条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:25:17