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

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

第一个日志包含正确的值

但是第二个日志说不同

为什么?

第一个日志:

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

第二个日志:

1920 248

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

暂无
暂无

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

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