Skip to content

Table 固定 head 滚动 body

September 28, 2024 by ccforeverd

如何在 Mantine 中实现 Table 固定 head 滚动 body

编写一个 Table 示例

首先看一下文档:

写的还是比较啰嗦的, 这里配合 @tanstack/react-table 一起使用, 会简洁很多

示例如下:

[
  {
    "position": 6,
    "mass": 12.011,
    "symbol": "C",
    "name": "Carbon"
  },
  {
    "position": 7,
    "mass": 14.007,
    "symbol": "N",
    "name": "Nitrogen"
  },
  {
    "position": 39,
    "mass": 88.906,
    "symbol": "Y",
    "name": "Yttrium"
  },
  {
    "position": 56,
    "mass": 137.33,
    "symbol": "Ba",
    "name": "Barium"
  },
  {
    "position": 58,
    "mass": 140.12,
    "symbol": "Ce",
    "name": "Cerium"
  }
]
Element positionElement nameSymbolAtomic mass
16CarbonC12.011
27NitrogenN14.007
339YttriumY88.906
456BariumBa137.33
558CeriumCe140.12

使用 position: sticky 实现

实现条件: (参考 stackoverflow)

  • table 外面有一层包裹, 用于实现滚动, 要有高度和 overflow: auto, 这里直接使用的 Table.ScrollContainer
  • thead 里面的 th 需要设置 position: sticky, top: 0, 这样可以固定在顶部 (需要加背景色)
  • 其他元素不用动