javascript - React 组件如何单独测量未知数量的子级,然后根据高度修改布局
问题描述
我正在寻找一种方法让一个组件渲染它的所有子元素,测量它们的高度,然后根据这些高度修改布局。例如,假设我有一个 Document 组件,其中包含多个(且数量未知)Paragraph 组件。我希望 Document 组件能够测量这些段落并在分页符所在的位置插入水平规则。
布局前:
<Document pageSize="A4" layout="portrait">
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<Paragraph text="some long text" />
</Document>
布局后:
<Document pageSize="A4" layout="portrait">
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<hr /><!-- End of page 1 -->
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<Paragraph text="some long text" />
<hr /><!-- End of page 2 -->
<Paragraph text="some long text" />
</Document>
我可以使用useClientRect()
Hooks FAQ 中的钩子来测量每个段落组件本身,但我不知道如何让 Document 组件访问该高度。任何建议将不胜感激!
我还想澄清一下,我希望在屏幕上提供有关打印时分页符位置的视觉反馈,类似于 Google Docs 或 MS Word 提供的反馈。
解决方案
我最近使用下面的代码做了类似的事情。我没有设置标准页面大小并插入 HR,而是让一堆瓷砖将它们的高度设置为相同。但是,它可能会为您指明正确的方向...
export const standardiseTiles = (className) => {
const nodes = [...document.getElementsByClassName(className)];
nodes.forEach(n => {
n.style.height = 'auto';
});
const maxHeight = nodes.reduce((p, c) => {
return c.clientHeight > p ? c.clientHeight : p;
}, 0);
nodes.forEach(n => {
n.style.height = `${maxHeight}px`;
});
};
我在 componentDidUpdate 中调用它,传入父容器的类名。
不完美,但它正在工作。
希望能帮助到你!