我有一个应用程序,我需要动态设置一个元素的高度(让我们说“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;

当前回答

在尝试了上面所有建议的解决方案后,没有运气,我发现我的一个元素在中间有CSS过渡,这就是为什么我不能得到正确的计算几何后道具改变。 所以我不得不使用onTransitionEnd监听器等待片刻,当尝试获得容器元素的DOM高度计算。 希望这能节省一些人的工作日,哈哈。

其他回答

只是用新的Hook方法来更新一下这个问题,你可以简单地使用useEffect钩子:

import React, { useEffect } from 'react'

export default function App(props) {

     useEffect(() => {
         // your post layout code (or 'effect') here.
         ...
     },
     // array of variables that can trigger an update if they change. Pass an
     // an empty array if you just want to run it once after component mounted. 
     [])
}

另外,如果你想在布局绘制之前运行,使用useLayoutEffect钩子:

import React, { useLayoutEffect } from 'react'

export default function App(props) {

     useLayoutEffect(() => {
         // your pre layout code (or 'effect') here.
         ...
     }, [])
}

我觉得这个解决方案很脏,但我们开始吧:

componentDidMount() {
    this.componentDidUpdate()
}

componentDidUpdate() {
    // A whole lotta functions here, fired after every render.
}

现在我就坐在这里,等着大家投反对票。

在我的经验窗口。requestAnimationFrame不足以确保DOM已经从componentDidMount完全渲染/ reflow-complete。我有代码运行,访问DOM后立即componentDidMount调用和使用单独的窗口。requestAnimationFrame将导致元素出现在DOM中;然而,对元素尺寸的更新还没有反映出来,因为回流还没有发生。

唯一真正可靠的方法是将我的方法包装在一个setTimeout和一个窗口中。requestAnimationFrame以确保React的当前调用堆栈在注册下一帧渲染之前被清除。

function onNextFrame(callback) {
    setTimeout(function () {
        requestAnimationFrame(callback)
    })
}

如果我不得不推测为什么这是发生的/必要的,我可以看到React批处理DOM更新,直到当前堆栈完成后才实际应用更改到DOM。

最终,如果你在React回调后触发的代码中使用DOM度量,你可能会想要使用这个方法。

对我来说,没有组合窗。requestAnimationFrame或setTimeout产生一致的结果。有时它会起作用,但并不总是如此——或者有时为时已晚。

我通过循环window来修复它。根据需要多次请求animationframe。 (一般为0 ~ 2 ~ 3次)

关键是diff > 0:在这里我们可以准确地确保页面何时更新。

// Ensure new image was loaded before scrolling
if (oldH > 0 && images.length > prevState.images.length) {
    (function scroll() {
        const newH = ref.scrollHeight;
        const diff = newH - oldH;

        if (diff > 0) {
            const newPos = top + diff;
            window.scrollTo(0, newPos);
        } else {
            window.requestAnimationFrame(scroll);
        }
    }());
}

您可以更改状态,然后在setState回调中进行计算。根据React文档,这是“保证在更新应用后触发”。

这应该在componentDidMount或代码中的其他地方完成(比如在调整大小事件处理程序上),而不是在构造函数中完成。

这是窗户的好替代品。它没有一些用户在这里提到的问题(需要结合setTimeout或多次调用它)。例如:

class AppBase extends React.Component {
    state = {
        showInProcess: false,
        size: null
    };

    componentDidMount() {
        this.setState({ showInProcess: true }, () => {
            this.setState({
                showInProcess: false,
                size: this.calculateSize()
            });
        });
    }

    render() {
        const appStyle = this.state.showInProcess ? { visibility: 'hidden' } : null;

        return (
            <div className="wrapper">
                ...
                <div className="app-content" style={appStyle}>
                    <List items={items} />
                </div>
                ...
            </div>
        );
    }
}