我有一个应用程序,我需要动态设置一个元素的高度(让我们说“app-content”)。它取应用程序的“chrome”的高度并减去它,然后设置“app-content”的高度以100%符合这些限制。这是超级简单的香草JS, jQuery,或骨干视图,但我努力弄清楚正确的过程将在React中这样做?

下面是一个示例组件。我想要能够设置应用内容的高度为窗口的100%减去动作栏和BalanceBar的大小,但我怎么知道什么时候所有的渲染和哪里我将把计算的东西在这个反应类?

/** @jsx React.DOM */
var List = require('../list');
var ActionBar = require('../action-bar');
var BalanceBar = require('../balance-bar');
var Sidebar = require('../sidebar');
var AppBase = React.createClass({
  render: function () {
    return (
      <div className="wrapper">
        <Sidebar />
        <div className="inner-wrapper">
          <ActionBar title="Title Here" />
          <BalanceBar balance={balance} />
          <div className="app-content">
            <List items={items} />
          </div>
        </div>
      </div>
    );
  }
});

module.exports = AppBase;

当前回答

我也遇到了同样的问题。

在大多数情况下,在componentDidMount()中使用类似hack的setTimeout(() =>{}, 0)是有效的。

但不是在特殊情况下;我不想使用ReachDOM findDOMNode,因为文档说:

注意:findDOMNode是一个用于访问底层DOM的escape hatch 节点。在大多数情况下,不鼓励使用这个逃生口,因为 它穿透了组件抽象。

(来源:findDOMNode)

所以在那个特定的组件中,我必须使用componentDidUpdate()事件,所以我的代码最终是这样的:

componentDidMount() {
    // feel this a little hacky? check this: http://stackoverflow.com/questions/26556436/react-after-render-code
    setTimeout(() => {
       window.addEventListener("resize", this.updateDimensions.bind(this));
       this.updateDimensions();
    }, 0);
}

然后:

componentDidUpdate() {
    this.updateDimensions();
}

最后,在我的例子中,我必须删除componentDidMount中创建的侦听器:

componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions.bind(this));
}

其他回答

我实际上遇到了类似行为的麻烦,我在一个组件中渲染了一个视频元素,它的id属性,所以当RenderDOM.render()结束时,它加载了一个需要id来找到占位符的插件,但它找不到它。

componentDidMount()中的setTimeout与0ms修复了它:)

componentDidMount() {
    if (this.props.onDidMount instanceof Function) {
        setTimeout(() => {
            this.props.onDidMount();
        }, 0);
    }
}

用ES6类代替React.createClass进行了一点更新

import React, { Component } from 'react';

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    // this code might be called when there is no element avaliable in `document` yet (eg. initial render)
  }

  componentDidMount() {
    // this code will be always called when component is mounted in browser DOM ('after render')
  }

  render() {
    return (
      <div className="component">
        Some Content
      </div>
    );
  }
}

另外,检查React组件生命周期方法:组件生命周期

每个组件都有很多类似componentDidMount的方法。

componentWillUnmount() -组件即将从浏览器DOM中删除

渲染之后,你可以像下面这样指定高度,并可以为相应的react组件指定高度。

render: function () {
    var style1 = {height: '100px'};
    var style2 = { height: '100px'};

   //window. height actually will get the height of the window.
   var hght = $(window).height();
   var style3 = {hght - (style1 + style2)} ;

    return (
      <div className="wrapper">
        <Sidebar />
        <div className="inner-wrapper">
          <ActionBar style={style1} title="Title Here" />
          <BalanceBar style={style2} balance={balance} />
          <div className="app-content" style={style3}>
            <List items={items} />
          </div>
        </div>
      </div>
    );`
  }

或者你可以使用sass指定每个react组件的高度。指定前2个react组件主div的固定宽度,然后第三个组件主div的高度为auto。因此,根据第三个div的内容,高度将被分配。

componentDidMount ()

此方法在呈现组件后调用一次。你的代码应该是这样的。

var AppBase = React.createClass({
  componentDidMount: function() {
    var $this = $(ReactDOM.findDOMNode(this));
    // set el height and width etc.
  },

  render: function () {
    return (
      <div className="wrapper">
        <Sidebar />
          <div className="inner-wrapper">
            <ActionBar title="Title Here" />
            <BalanceBar balance={balance} />
            <div className="app-content">
              <List items={items} />
          </div>
        </div>
      </div>
    );
  }
});

我不会假装我知道为什么这个函数可以工作,但是window。当我需要在useEffect中使用Ref访问DOM元素时,getComputedStyle 100%的时间为我工作-我只能假设它将与componentDidMount一起工作。

我把它放在useEffect代码的顶部,它似乎迫使效果等待元素被绘制,然后再继续下一行代码,但没有任何明显的延迟,如使用setTimeout或异步睡眠函数。如果没有这个,当我试图访问Ref元素时,它将返回为未定义。

const ref = useRef(null);

useEffect(()=>{
    window.getComputedStyle(ref.current);
    // Next lines of code to get element and do something after getComputedStyle().
});

return(<div ref={ref}></div>);