【问题标题】:How to get div or element height in ReactJS如何在 ReactJS 中获取 div 或元素高度
【发布时间】:2021-06-16 16:36:37
【问题描述】:

我正在尝试在 reactJS 中获取 div 元素,但我无法实现它。我需要一些专家来查看我的代码并解决我的问题或新代码 sn-p 将不胜感激。

谢谢

代码

    this.divElement = React.createRef()

    const height = this.divElement.clientHeight
    this.setState({ height })

     <div
      className="col-2-3"
      ref={(divElement) => {
      this.divElement = divElement
      }}
      >
     </div>

【问题讨论】:

  • 尝试在componentDidMount 方法中设置状态。
  • 这能回答你的问题吗? ReactJS - Get Height of an element
  • @MaheerAli 我在 componentDidmount 中做。
  • @WaisKamal no ,实际上我遵循评论中提到的相同但无法找到解决方案

标签: javascript arrays reactjs ecmascript-6


【解决方案1】:

您应该使用current 属性:

this.divElement = React.createRef()

const height = this.divElement.current.clientHeight
this.setState({ height })

 <div
  className="col-2-3"
  ref={this.divElement}
  >
 </div>

【讨论】:

  • TypeError: 无法读取 null 的属性“clientHeight”
  • 看起来你试图在填充 ref 之前获取高度在 componentDidMount 中尝试相同
  • 是的,它在componentDidMount中
猜你喜欢
  • 2016-05-11
  • 2018-09-18
  • 2017-10-02
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
相关资源
最近更新 更多