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
相关产品推荐
相关产品推荐

