我应该如何处理 React 的 componentWillUnmount 中的离开动画?

How should I handle a leave animation in componentWillUnmount in React?

我想知道是否有人可以提供一些关于他们如何处理 React.js 中的离开动画的见解。我一直在使用 Greensock TweenMax,输入动画在 componentDidMount 上运行良好,但我还没有找到一种可靠的方法来为组件制作动画。

我的感觉是它应该放在 componentWillUnmount 中,但是 React 没有提供回调机制来指示您何时准备好放弃一个组件。因此,过渡动画永远不会完成,因为动画与 React 异步。相反,您会看到一小部分动画,组件消失,并被下一个动画组件取代。

这是我从 9 个月前开始使用 React 以来一直在努力解决的问题。我忍不住认为除了 ReactCSSTransitionGroup 之外必须有一个解决方案,我发现它既麻烦又挑剔,尤其是对于 react-router。

ReactTransitionGroupReactCSSTransitionGroup 建立在其上)是允许异步进入和离开的基础组件。它提供了生命周期挂钩,您可以使用它来挂接到 JS-based 动画。 The docs list 允许的钩子:

ReactTransitionGroup is the basis for animations. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them. There are 3 ways to get starting using ReactCSSTransitionGroups:

import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // ES6
var ReactCSSTransitionGroup = require('react-addons-css-transition-group') // ES5 with npm
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; // ES5 with react-with-addons.js

componentWillAppear(callback)

This is called at the same time as componentDidMount() for components that are initially mounted in a TransitionGroup. It will block other animations from occurring until callback is called. It is only called on the initial render of a TransitionGroup.

componentDidAppear()

This is called after the callback function that was passed to componentWillAppear is called.

componentWillEnter(callback)

This is called at the same time as componentDidMount() for components added to an existing TransitionGroup. It will block other animations from occurring until callback is called. It will not be called on the initial render of a TransitionGroup.

componentDidEnter()

This is called after the callback function that was passed to componentWillEnter is called.

componentWillLeave(callback)

This is called when the child has been removed from the ReactTransitionGroup. Though the child has been removed, ReactTransitionGroup will keep it in the DOM until callback is called.

componentDidLeave()

This is called when the willLeave callback is called (at the same time as componentWillUnmount).

Animation - Low-level API

为了制作 child 动画,您需要在 componentWillLeave 中开始动画,并在动画完成时调用提供的 callback。例如,here's a JSFiddle showing a component that stagger-animates its children in and out: http://jsfiddle.net/BinaryMuse/f51jbw2k/

动画输出的相关代码为:

componentWillLeave: function(callback) {
  this._animateOut(callback);
},

_animateOut(callback) {
  var el = ReactDOM.findDOMNode(this);
  setTimeout(function() {
    TweenLite.to(el, 1, {opacity: 0}).play().eventCallback("onComplete", callback);
  }, this.props.animateOutDelay);
},

查看 React-Motion

https://www.youtube.com/watch?v=1tavDv5hXpo

Cheng Lou 是 React 团队的开发人员。

他谈到了当前 ReactCSSTransitionGroup 的问题。

他开发了 React-Motion 来解决这个问题。

虽然它没有使用 css transitions ,但它似乎表现不错并且非常确定。 ReactCSSTransitionGroup 似乎很挑剔,因为你不能中断转换。