首页 > 解决方案 > 表格中的粘性位置在 ReactJs 中不起作用

问题描述

我想theader在滚动时使表格保持粘性,以便在滚动时始终看到表格的标题。

我试试这个,但它什么也没做。

反应渲染:

<table class="table text-center align-middle" style={{ width: this.state.PercentTable }}>
    <thead class="bgColor stickyHeader">
        <tr>
            <th style={{ width: "3%", paddingRight: "0" }}></th>
            <th style={{ width: this.state.PercentCell }}></th>
                {list_1}
        </tr>
     </thead>
     {list_2}
</table>

CSS 样式:

.stickyHeader {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
}

该表不在视图的顶部(这就是我想要粘性而不是固定的原因)。

这是一个工作示例:工作示例

谢谢你的帮助。

标签: cssreactjssticky

解决方案


有很多方法可以实现这一目标。我推荐有一个 npm 包,可以节省你的时间和精力。检查一下:react-sticky-table-thead 你所要做的就是在你的桌子周围包裹一个组件,比如:

<StickyHeader>
  <table>
    <thead>
      <tr><th>Head</th></tr>
    </thead>
    <tbody>
      <tr><td>Data</td></tr>
    </tbody>
  </table>
</StickyHeader>

推荐阅读