代码之家  ›  专栏  ›  技术社区  ›  batatop

React.js公司-有可能在第一次渲染之前得到元素的大小吗?

  •  0
  • batatop  · 技术社区  · 6 年前

    为了给您一个更可靠的例子,我想在这些元素的中心放置一个动态文本:

    getLabels = () =>
     this.props.labels.map(labelObj => {
      const labelPosition = this.getValueWidth(labelObj.pos);
      const labelPositionText = `${labelPosition}%`;
      return (
        <div
          style={{
            position: 'absolute',
            backgroundColor: 'grey',
            zIndex: 2,
            left: labelPositionText,
            height: this.props.labelStyle.height,
            width: this.props.labelStyle.width,
            marginLeft: (this.props.labelStyle.width / 2) * -1,
            marginTop: ((this.props.labelStyle.height - this.props.height) / 2) * -1,
            borderRadius: 100,
          }}
        />
      );
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Vencovsky    6 年前

    我试图在元素到达DOM之前计算元素的宽度

    由于可以在元素上添加样式,所以在将其添加到dom之前不能计算宽度。

    但你可以尝试一些解决办法。

    你应该用 useLayoutEffect

    签名与useEffect相同,但它在所有DOM突变之后同步触发。使用它从DOM读取布局并同步重新呈现。将同步刷新useLayoutEffect中计划的更新, 在浏览器有机会画画之前。

    这意味着您可以在浏览器在DOM上绘制元素之前计算宽度。