1, 在react工程中下载安装过渡动画模块
npm install react-transition-group --save
2, 在路由配置文件/src/router/index.js中导入动画组件
import { TransitionGroup, CSSTransition } from "react-transition-group"
3, 在路由组件模板中,用动画组件包裹路由组件
<TransitionGroup>
<CSSTransition timeout={2000} classNames="wuyifan" unmountOnExit key={props.location.pathname}>
<Switch location={props.location}>
<Route exact path="/user" component={User} />
</Switch>
</CSSTransition>
</TransitionGroup >
注意: CSSTransition组件的key属性要保证唯一性,所以用location.pathname
Switch 组件要设置location属性为路由信息的props.location, 保证路由跳转组件的key和CSSTransition的key一致
4, 路由组件中没有路由信息location.pathname, 需要使用withRouter导入
import { withRouter } from "react-router-dom"
export default withRouter(MyRouter)
5, 在组件的css文件中写路由切换动画过程
/* 入场动画过程 */
.wuyifan-enter{
transform: translateX(200px)
}
.wuyifan-enter-active{
transition: 2s;
transform: translateX(0px)
}
.wuyifan-enter-done{
transform: translateX(0px)
}
/* 出场动画过程 */
.wuyifan-exit{
transform: translateX(0px)
}
.wuyifan-exit-active{
transition: 2s;
transform: translateX(200px)
}
.wuyifan-exit-done{
transform: translateX(200px)
}
.home, .user, .login, .animate{
position: absolute;
left: calc(50% - 200px)
}