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

Ama*_*ira 2 height components render reactjs

所以,大家好,基本上我正在使用react,我想通过props获取父div的高度,并使它的孩子具有相同的高度。每次调整窗口大小时,父div都会渲染。我尝试使用componentDidMountsetState获取父级的高度,但componentDidMount仅在父级div第一次渲染时才被调用。

而且我不能使用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;
Run Code Online (Sandbox Code Playgroud)

fku*_*kov 5

您必须在3个地方state以新高度更新父母的位置:

  1. componentDidMount在第一次renderdiv实际是父母的第一次出现)之后会被调用。
  2. componentDidUpdaterenderpropsstate更新引起的-ing 后调用。仅当您实际使用任何工具时props,才需要这样做,并且它们的更新可能会导致div的高度变化。
  3. 调整窗口大小。

您必须使用方法内部refs获取parent div的DOM元素render。之后,您可以在componentDidMount和中使用它componentDidUpdate(请检查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'));
Run Code Online (Sandbox Code Playgroud)

工作示例可以在这里找到。