javascript - react .js : Set sticky table-header cell width based on corresponding table-row cell width

标签 javascript html css reactjs

目标

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

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

问题

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

你可以在这里看到问题和我的测试代码: https://codesandbox.io/s/y0jx5rp081

注意事项

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

最佳答案

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

constructor(props) {
  ...
  this.bodyRef = React.createRef()
}

将其作为 prop 传递给表体。

<tbody
  ...
  ref={this.bodyRef}
>

然后在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
  });
}

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

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

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

Edit React Sticky Table-Header

关于javascript - react .js : Set sticky table-header cell width based on corresponding table-row cell width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51597713/

相关文章:

javascript - 使用 jquery 在 div 中添加、调整大小、位置、颜色更改文本

css - Angular 2 组件无法从外部 css 皮肤加载相对背景图像 url

javascript - 如何使用 Action razor 语法在 ajax url 中使用 var

javascript - Node.js mongodb 驱动程序异步/等待查询

javascript - ObservableArray 未按预期工作

javascript - OrbitControls.js 导致模型在点击旋转时消失

html - DIV 没有放在单元格的顶部

php - 将变量从 js 发送到表单,然后发送到 php 文件

html - 如何去除 HTML 内容周围的边距?

css - IE 忽略 2 个水平 div 之间的边距