【问题标题】:Get component's height every time it renders每次渲染时获取组件的高度
【发布时间】:2017-08-16 08:09:00
【问题描述】:

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

我不能在render()function 中使用ReactDOM.findDOMNode(this).clientHeight

为简化起见,以下是步骤:

  • (每次)调整窗口大小
  • Div1 被渲染
  • 获取 Div1 高度并设置它的状态
  • 通过 props 将其传递给 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;

【问题讨论】:

  • 你能分享最少的代码以确保每个人都能理解吗?您“尝试使用 componentDidMount 和 setState 来获取父级的高度”:来自 div1 或 div 2?
  • 你试过了吗shouldComponentUpdate()facebook.github.io/react/docs/…
  • @DamienLeroux 我在那里放了一些代码,谢谢。我从 div1 使用
  • @DivyanshuMaithani 其实我不知道这个方法,但是通过简短的阅读,我仍然不知道如何进行我想要的更新。

标签: reactjs height components render


【解决方案1】:

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

  1. componentDidMount 将在第一个 render 之后调用(实际上会出现第一次父母的 div)。
  2. componentDidUpdaterender-ing 之后调用,由propsstate 更新引起。只有当您实际使用任何 props 并且它们的更新可能导致 div 的高度发生变化时,您才需要这样做。
  3. 调整窗口大小。

您必须使用refsrender 方法中获取父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找到工作示例。

【讨论】:

  • 非常感谢!这正是我想要的!只是一个问题,使用 refs 没有任何问题吗?
  • 根据我的经验并没有太多。请记住,this.div 可以是undefined,以防render 方法中有一些条件逻辑阻止&lt;div&gt; 成为返回树的一部分。还要检查在 React docs 中使用 refs 的其他注意事项
猜你喜欢
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2021-08-11
  • 1970-01-01
  • 2010-10-06
相关资源
最近更新 更多