简体   繁体   English

React.js - 是否可以在第一次渲染之前获取元素的大小?

[英]React.js - Is it possible to get the size of an element before the first render?

I'm trying to get an element's width before render.我试图在渲染之前获取元素的宽度。 I need it because I will position the element based on it's current width.我需要它,因为我将根据元素的当前宽度定位元素。 The element contains a dynamic text so it doesn't have a constant width.该元素包含动态文本,因此它没有恒定的宽度。

To give you a more solid example, I want to position a dynamic text at the center of these elements:为了给你一个更可靠的例子,我想在这些元素的中心放置一个动态文本:

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,
      }}
    />
  );
});

I'm trying to find a way to calculate the element's width before it reaches to the DOM我试图找到一种方法来计算元素到达 DOM 之前的宽度

You can't.你不能。

Because of the styles that can be added on your element, you can't calculate the width before you add it to the dom.由于可以在元素上添加样式,因此在将其添加到 dom 之前无法计算宽度。

But there is some solutions you can try.但是您可以尝试一些解决方案。

You should use useLayoutEffect .您应该使用useLayoutEffect

The signature is identical to useEffect, but it fires synchronously after all DOM mutations.签名与 useEffect 相同,但在所有 DOM 突变后同步触发。 Use this to read layout from the DOM and synchronously re-render.使用它从 DOM 读取布局并同步重新渲染。 Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.在浏览器有机会绘制之前, useLayoutEffect 内计划的更新将同步刷新

These means you can calculate the width before the browser paint the element on the DOM.这意味着您可以在浏览器在 DOM 上绘制元素之前计算宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM