我希望能够在组件的属性或状态更改时在组件上运行一个简单的淡入淡出动画(反应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或任何其他软件包是否有可能。
我感觉我将不得不销毁整个组件并构建一个新组件,从外观上看,我们仍然拥有许多工具来控制componentWillMount
,componentWillUnmount
,React的行为-transition-group ...等...但是当它是如此微小的更新时,销毁它实在是太糟糕了。