【问题标题】:React, how to get size of element immediately after update the DOMReact,如何在更新 DOM 后立即获取元素的大小
【发布时间】: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


【解决方案1】:

不确定是什么触发了componentDidUpdate(),但使用componentDidMount() 作为参考,我会像这样构造你的元素参考:

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/

【讨论】:

    【解决方案2】:

    我认为问题出在你的div

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

    它没有内容,所以宽度/高度将等于0。

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 2022-10-12
      • 2022-11-10
      • 1970-01-01
      • 2019-11-15
      • 2021-08-18
      • 2020-10-16
      • 2012-08-14
      • 2021-11-11
      相关资源
      最近更新 更多