【发布时间】:2019-06-17 17:02:11
【问题描述】:
我想在更新props后获取元素大小,所以我尝试通过componentDidUpdate()获取它,但每次它都为我返回0
我写了一个组件,由它的父组件控制,在父组件中,调用了一个setState语句来改变我的组件的props。
然后,我想在props更改后立即获取组件中div的大小,所以我将代码放在componentDidUpdate()中,但是clientHeight和getBoundingClientRect()都返回0,实际上它的高度和宽度肯定是不是 0。
/*index.js*/
import React, { Component } from 'react'
class MyTL extends Component{
constructor(props){
super(props)
}
componentDidMount(){
this.root = this.refs.tl
}
componentDidUpdate(){
if(this.props.t){
// this.root = this.refs.tl // I tried to get root here, but not worked
console.log(this.root.clientHeight)
console.log(this.root.getBoundingClientRect())
}
}
render(){
return (
<div className='tr_c', refs='tl'></div>
)
}
/* style.less*/
.tr_c{
height:100%;
width:100%;
}
我希望控制台输出 '290px',但它给了我 0
这里不能确定尺寸吗?请帮帮我。
【问题讨论】:
-
会为您的目的使用 ID 而不是 ref 吗?你可以使用
document.getElementById。我试过这个,它可以在 componentDidUpdate 上获得高度 -
@BrooklinMyers 不应在 React 组件中使用
document.getElementById
标签: javascript reactjs