[英]React, how to get size of element immediately after update the DOM
I want to get element size after updating the props, so I tried to get it through componentDidUpdate(), but each time it returns 0 for me 我想在更新道具后获取元素大小,因此我尝试通过componentDidUpdate()获取它,但是每次它为我返回0时
I wrote a component that controlled by its father component, in father component, a statement of setState is called, to change my component's props. 我编写了一个由其父组件控制的组件,在父组件中,调用setState的语句来更改组件的道具。
Then, I want to get size of a div in my component immediately after the props changed, so I put my code in componentDidUpdate(), but both clientHeight and getBoundingClientRect() return 0, actually, its height and width are definitely not 0. 然后,我想在更改道具后立即在组件中获取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%;
}
I expected an console output '290px', but it gave me 0 我期望控制台输出为“ 290px”,但它给了我0
Is it not possible to get size here? 在这里无法获得尺寸吗? please help me.
请帮我。
Not sure what is triggering the componentDidUpdate()
, but using componentDidMount()
for a reference, I would structure your element ref like such: 不知道是什么触发了
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/ jsFiddle: https ://jsfiddle.net/dzuwan13/
I think problem is in your div
我认为问题出在您的
div
<div className='tr_c', refs='tl'></div>
It has no contents, so Width/Height will be equals 0. 它没有内容,因此Width / Height等于0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.