在路由跳转过程中添加动画效果,比如简单的fadeIn,fadeOut等,我的方法是用'react-addons-transition-group'来做。比如
<App>
<ReactTransitionGroup component="div">
{this.props.children}
</ReactTransitionGroup>
</App>
对应的children
组件里添加一些过渡hook,比如
class Children extends Component {
componentWillUnmount() {
clearTimeout(this.enterTimer);
clearTimeout(this.leaveTimer);
}
componentWillAppear(callback) {
this.initAnimation(callback);
}
componentWillEnter(callback) {
this.initAnimation(callback);
}
componentDidAppear() {
this.animate();
}
componentDidEnter() {
this.animate();
}
componentWillLeave(callback) {
const style = this.component.style;
style.opacity = 0;
this.leaveTimer = setTimeout(callback, 0);
}
animate() {
const style = this.component.style;
const opacity = 'opacity 1000ms cubic-bezier(0.23, 1, 0.32, 1) 0ms';
style.opacity = 1;
style.transition = opacity;
}
initAnimation(callback) {
const style = this.component.style;
style.opacity = 0;
this.enterTimer = setTimeout(callback, 0);
}
render() {
return <div>嘿嘿嘿</div>;
}
}
事实上,在路由切换的时候什么也没发生,钩子函数根本没有被调用。只有在组件在第一次加载时才有动画效果,而路由切换时无。谢谢大家!
两个方案:
1、全局挂载动画组件
在全局挂载动画组件,比如
Nprogress
;在路由切换时,可以获取到上一个页面的
onLeave
方法(这个方法是react-router
的api
),在这个方法中调用NProgress.start()
;然后在每一个路由配置中,即
react-router
中的component
使用按需加载,即require.ensure
或者react-router-proxy
;在路由的
component
组件的入口处(是module
的全局而非class
的constructor
)执行Nprogress.done(true)
;2、将
state
挂载全局将全局唯一的
state
(可以是挂载在redux
上的state
,也可以直接挂载在window
对象上)作为动画加载标识;在路由的
component
中的componentWillUnmount
中修改标识为动画中,componentWillMount
中修改标识为加载动画;监听全局的
state
的改变,触发顶层挂载的动画组件的变化;总结:
大概就是两种模式:观察者模式,或者发布订阅模式。