每次渲染时获取组件的高度

时间:2017-03-23 16:22:43

标签: reactjs height components render

所以嘿伙计们,基本上我正在使用反应,我想得到父div的高度,并通过道具让它的孩子拥有相同的高度。每次调整窗口大小时,父div都会呈现。我尝试使用componentDidMountsetState来获取父级的高度,但仅在我的父div渲染时调用componentDidMount

我无法在ReactDOM.findDOMNode(this).clientHeight函数中使用render()

为简化起见,这些步骤如下:

  • (每次)窗口调整大小
  • Div1渲染
  • 获取Div1高度并设置状态
  • 通过道具传递给Div2。

有什么想法吗?

这是一段代码:

import React, { Component } from 'react';
import Div2 from './Div2';

    class Div1 extends Component {
      constructor(props){
        super(props);
        this.state = {
          height: 0
        };
      }

      componentDidMount() {
      var height = (ReactDOM.findDOMNode(this).clientHeight);
      this.setState({height: height})
      }    

      render() { 
         return(    
          <div className='Div1'>    
            <Div2 height={this.state.height}/>   
          </div>    
      );
      }
    }

    export default Div1;

1 个答案:

答案 0 :(得分:3)

您必须在3个地方更新父亲state的新身高:

  1. componentDidMount将在第一个render之后调用(第一次父母div将实际出现)。
  2. componentDidUpdaterender更新引起的props之后调用的
  3. state。您只有在实际使用任何props时才需要这样做,而且他们的更新可能会导致div的身高变化。
  4. 窗口调整大小。
  5. 您必须使用refsdiv方法中获取父render个DOM元素。之后,您可以在componentDidMountcomponentDidUpdate中使用它(请查看React Component Lifecycle文档)。

    将所有内容组合在一起产生以下代码,其中Foo将其根div高度传递给Bar

    class Bar extends React.Component {
      render() {
        return (
          <div className='bar' style={{height: `${this.props.height / 2 }px`}} />
        );
      };
    };
    
    class Foo extends React.Component {
      constructor() {
        super();
        this.state = { height: 0 };
        this.updateHeight = this.updateHeight.bind(this);
      }
    
     componentDidMount() {
       this.updateHeight();
       window.addEventListener("resize", this.updateHeight);
     }
    
     componentWillUnmount() {
       window.removeEventListener("resize", this.updateHeight);
     }
    
     componentDidUpdate() {
       this.updateHeight();
     }
    
     updateHeight() {
       if (this.state.height != this.div.clientHeight)
         this.setState({ height: this.div.clientHeight })
     }
    
     render() {
        return (
          <div ref={ div => { this.div = div; } } className='foo'>
            <Bar height={this.state.height} />
          </div>
        );
      }
    }
    
    ReactDOM.render(<Foo/>, document.getElementById('app'));
    

    可以找到工作示例here