您可以控制React更新组件的时间吗?

时间:2019-07-16 17:53:26

标签: reactjs react-16

我希望能够在组件的属性或状态更改时在组件上运行一个简单的淡入淡出动画(反应16.8.6)。

有问题的组件有一个简单的任务:显示一行在props中传递的文本。问题在于,当组件检测到与旧道具的差异时,该值会立即替换,从而阻止我播放淡入淡出的动画。

我已经玩过各种React lifecycle methods来控制何时准确地做出反应将旧值替换为新值而没有成功。

import React, { Component } from 'react';
import classname from 'classnames';

import styles from './styles.module.scss'; // Styles with all the nice transitions.

class MyComponent extends Component {
  componentDidMount() {
    this.setState({
      location: this.props.location,
      hidden: false,
    });
  }

  // Desired implementation
  onUpdate(nextProps) {
    // Hide the text.
    this.setState({ hidden: true });

    // *** Wait for the end of the animation. ***

    // Replace the text and reveal it.
    this.setState({
      location: nextProps.location,
      hidden: false,
    });
  }

  render () {
    const classNames = classname(
      styles.text, // Always present.
      {
        [styles.faded]: this.state.hidden, // styles.faded will be added if this.state.faded is truthy
      }
    );

    return (
      <div className={styles.wrapper}>
        <span className={classNames}>
          {this.state.location}
        </span>
      </div>
    );
  }
}

我想知道React 16.x.x或任何其他软件包是否有可能。

我感觉我将不得不销毁整个组件并构建一个新组件,从外观上看,我们仍然拥有许多工具来控制componentWillMountcomponentWillUnmount,React的行为-transition-group ...等...但是当它是如此微小的更新时,销毁它实在是太糟糕了。

0 个答案:

没有答案