简体   繁体   English

无法通过 react ref 获得正确的 clientWidth 或 clientHeight

[英]Can not get correct clientWidth or clientHeight with react ref

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>
    )
}

I want to get width and height of an element我想获取元素的宽度和高度

The first log contains correct values第一个日志包含正确的值

But the second log says different但是第二个日志说不同

Why?为什么?

first log:第一个日志:

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

second log:第二个日志:

1920 248

Now I have figured it out, chrome console log sometime is very slow, by the time it logs, the width and height already changed.现在我弄明白了,chrome 控制台日志有时很慢,到它记录时,宽度和高度已经改变了。

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

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