简体   繁体   中英

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

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.

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.

/*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

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:

 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/

I think problem is in your div

<div className='tr_c', refs='tl'></div>

It has no contents, so Width/Height will be equals 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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