为什么 div ref 的 offsetHeight 属性在 componentDidMount或 componentDidUpdate之后不同?

问题描述

我有一个组件:

class MyComponent ...{

  private bodyRef = React.createRef<HTMLdivelement>();

  componentDidMount() {
    console.log(this.bodyRef.current?.offsetHeight);
  }

  render() {
     return <div>
        <VerticalLine height={this.bodyRef.current?.offsetHeight}>
        <div id={'content-body'} ref={this.bodyRef}>
          ...
        </div>
      </div>
  }

}

当我检查元素时,浏览器 (chrome) 告诉我该元素的高度为 103px,但控制台在 98(或 componentDidMount .

如果我添加一个

componentDidUpdate

并单击它,然后它会打印正确的高度。

但是,这不是很奇怪吗?我的意思是 <button onClick={() => console.log(this.currentRef?.offsetHeight)} /> componentDidMount 的目的应该表明 html 已被绘制/重新绘制,不是吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)