【问题标题】:Can not get correct clientWidth or clientHeight with react ref无法通过 react ref 获得正确的 clientWidth 或 clientHeight
【发布时间】:2019-09-17 21:23:07
【问题描述】:
constructor(props) {
    super(props)
    this.ref = React.createRef()
}

componentDidMount() {
    const { clientWidth, clientHeight } = this.ref.current
    console.log(this.ref.current)
    console.log(clientWidth, clientHeight)
}

render() {
    return (
        <div ref={this.ref} style={{width: '100%', height: '100%'}}></div>
    )
}

我想获取元素的宽度和高度

第一个日志包含正确的值

但是第二个日志说的不一样

为什么?

第一个日志:

clientHeight:783
clientLeft:0
clientTop:0
clientWidth:1385

第二个日志:

1920 248

【问题讨论】:

  • 这可能不足以调试问题。我创建了一个简单的代码沙箱,其行为符合预期:codesandbox.io/s/ppr0qxx73x。如果您调整视图区域的大小,您将看到宽度按预期更新(检查代码沙箱内置控制台)
  • 尝试在componentDidUpdate 上调用它。问题是当您记录 this.ref.current 时,记录的对象显示在记录后发生的对象的突变,而 clientWidth 和 clientHeight 仅在 componentDidMount 上共同计算一次。
  • Chrome 记录器正在记录对象的引用。为了更好地理解它,您可以在 componentDidMount 中使用 JSON.stringify 记录它
  • 你的第一个日志产生的输出与我在这里的类似代码不同:codesandbox.io/s/8l94r1p2w8 ............你能看看是否我错过了一些东西。
  • 这是您实际使用的代码吗?如果您有 img,则加载图像后高度可能会发生变化

标签: javascript html reactjs google-chrome dom


【解决方案1】:

现在我想通了,chrome控制台日志有时很慢, 到它记录的时候,宽度和高度已经改变了。

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 2020-11-21
    • 2022-07-11
    相关资源
    最近更新 更多