React.js:根据相应的表行单元格宽度设置粘性表头单元格宽度

Zac*_*ach 5 html javascript css reactjs

目标

我想创建一个带有滚动体和粘性标题的表。表标题单元格的宽度需要匹配其对应的正文列宽度。

它在React中,并且Table组件包含两个单独的组件(一个用于标题,另一个用于主体中的行)。组件的内容将来自外部来源,因此我无法对任何宽度进行任何假设。表格的主体将包含很多行,因此表格标题将需要保持粘性并保持在顶部。

问题

虽然表主体中列的宽度是自动设置的,但表头中的宽度不会自动设置。需要根据表的内容自动设置表标题的宽度。

您可以在此处查看问题和我的测试代码:https : //codesandbox.io/s/y0jx5rp081

注意事项

  • 如果有足够的理由,我愿意使用插件或库,但如果可能的话,我宁愿不使用
  • 我已经尝试过react-sticky,它不支持表格格式
  • 我还尝试了react-sticky-table,这不允许我将表拆分为行组件,这是我需要做的,以帮助更有效地呈现
  • 再一次,我需要所有宽度自动设置。到目前为止,我看到的唯一解决方案包括手动设置标题中的宽度

Jem*_*alo 2

您可以通过在渲染后查询表格单元格来获取表格单元格的宽度。要在渲染后访问 React 组件,我们需要使用 ref。

constructor(props) {
  ...
  this.bodyRef = React.createRef()
}
Run Code Online (Sandbox Code Playgroud)

将其作为支柱传递给桌体。

<tbody
  ...
  ref={this.bodyRef}
>
Run Code Online (Sandbox Code Playgroud)

然后在componentDidMount中渲染后就可以访问了。如果您删除、添加或编辑行,您可能也想在 componentDidUpdate 中执行此操作(但请注意不要进行无限循环)。

componentDidMount() {
  const row = this.bodyRef.current.children[0].children; // Get the children of one <tr>
  // the path from this.bodyRef.current to the children you need may vary.
  const headerWidths = [];
  for (let i = 0; i < row.length; i += 1) {
    headerWidths.push(row[i].getBoundingClientRect().width); // Get the rendered width of the element.
  }
  this.setState({
    headerWidths
  });
}
Run Code Online (Sandbox Code Playgroud)

然后只需使用您所在州的宽度值即可。

constructor(props) {
  ...
  this.state = {
    ...
    headerWidths: []
  }
}
...
render() {
  return (
    ...
    <th style={{ width: this.state.headerWidths[index] }}>
      ...
    </th>
  )
}
Run Code Online (Sandbox Code Playgroud)

这是您的方便示例的工作版本。

编辑 React 粘性表头