一、效果演示
react-transition-group转场动画:
(如果无法播放可点击下载查看)
二、安装
这个演示界面是通过路由实现的,谈到这个我们就不得不提到成熟的react动画库:react-transition-group
首先我们通过npm进行安装(这里假定你已经学会了使用react-router-dom,react-router,react-router-config)如果你还没有学习,那我建议你稍微进行学习后再来了解路由动画。
安装命令:
npm install react-transition-group --save
三、完整源码
不想看实现过程的请直接看源码实现并进行copy:
index.js:
import React from "react";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import { Switch, Route, withRouter } from "react-router-dom";
import "./index.css";
/**
*
* @param {way} props
* @description 用于页面路由跳转 通过way指定跳转方式,指定way=refade
* 则反向
*
*/
const ANIMATION_MAP = {
PUSH: "fade",
POP: "refade",
};
function AnimationGo(props) {
const { children } = props;
// console.log(props.history.action);
// 根据动作自行判断前进和后退
/*使用React.cloneElement API对props中的classNames这一props进行修改 */
return (
<Route
render={({ location }) => (
<TransitionGroup
childFactory={(child) =>
React.cloneElement(child, {
classNames: ANIMATION_MAP[props.history.action],
})
}
>
<CSSTransition timeout={500} key={location.pathname}>
<Switch location={location}>{children}</Switch>
</CSSTransition>
</TransitionGroup>
)}
></Route>
);
}
export default withRouter(AnimationGo);
index.css
/* 入场动画开始 */
.fade-enter,.fade-appear {
transform: translateX(100%);
}<