gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:12:41 25 4
gpt4 key购买 nike

目标

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

它在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com