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

Get component's height every time it renders

所以大家好,基本上我使用的是 React,我想通过道具获得父级 div 的高度,并使其子级具有相同的高度。每次 window 调整大小时,父 div 都会呈现。我尝试使用 componentDidMountsetState 来获取父级的高度,但是 componentDidMount 仅在我的父级 div 第一次渲染时被调用。

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

为简化起见,步骤如下:

有什么想法吗?

这是一段代码:

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;

有 3 个地方你必须用新高度更新你的 parent 的 state

  1. componentDidMount 将在第一个 render 之后调用(第一次 parent 的 div 将实际出现)。
  2. componentDidUpdatepropsstate 更新引起的 render-ing 之后调用。仅当您实际使用任何 props 并且它们的更新会导致 div 的高度变化时,您才需要这样做。
  3. window 调整大小。

您必须使用 refsrender 方法中获取 parent div 的 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