[英]React, how to get size of element immediately after update the DOM
我想在更新道具后获取元素大小,因此我尝试通过componentDidUpdate()获取它,但是每次它为我返回0时
我编写了一个由其父组件控制的组件,在父组件中,调用setState的语句来更改组件的道具。
然后,我想在更改道具后立即在组件中获取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
在这里无法获得尺寸吗? 请帮我。
不知道是什么触发了componentDidUpdate()
,但是使用componentDidMount()
作为参考,我会像这样构造您的元素ref:
class MyTL extends React.Component { constructor(props) { super(props); this.tl = React.createRef(); } componentDidMount() { console.log(this.tl.current.getBoundingClientRect()); console.log(this.tl.current.clientHeight); } render() { return ( <div className='tr_c' ref={this.tl}> <p>Stuff</p> </div> ) } } ReactDOM.render(<MyTL />, document.querySelector("#app"));
.tr_c { background: #ccc; height: 250px; width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>
jsFiddle: https ://jsfiddle.net/dzuwan13/
我认为问题出在您的div
<div className='tr_c', refs='tl'></div>
它没有内容,因此Width / Height等于0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.