react-transition-group配合css透明度变化,实现页面顺滑跳转。
效果:
1.安装依赖包 react-transition-group
2.引入组件
import { TransitionGroup, CSSTransition } from 'react-transition-group';
3.指定前进和后退的标识,和切换期间时长
const ANIMATION_MAP = { PUSH: 'forward', POP: 'back', }; const _timeout = 1000;
ANIMATION_MAP[history.action]为指定CSSTransition的样式
外加css代码进行透明度调整切换
//动态透明度变动效果 .animate-route { animation-duration: 1s; animation-fill-mode: both; animation-name: fadeRoute; } @keyframes fadeRoute { from { opacity: 0; } to { opacity: 1; } }
将animate-route放在页面切换的父元素上即可
完整代码:
layout.jsx
/** * layout布局组件 * 可插入全局组件 */ import React from 'react'; import Local from './local'; import { withRouter } from 'umi'; import styles from './index.less'; import './cssTransition.less'; //引入动画库的俩个组件 import { TransitionGroup, CSSTransition } from 'react-transition-group'; const ANIMATION_MAP = { PUSH: 'forward', POP: 'back', }; const _timeout = 1000; /** * layout布局组件 */ const Layouts = (props) => { const { location, children, history } = props; const classNames = ANIMATION_MAP[history.action]; return ( <> <TransitionGroup> <CSSTransition key={location.pathname} timeout={_timeout} classNames={classNames} > <div className={`${styles.layouts} ${styles['animate-route']}`}> {children} <Local /> </div> </CSSTransition> </TransitionGroup> </> ); }; export default withRouter(Layouts);
index.less
//禁止选中复制 .layouts { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } //动态透明度变动效果 .animate-route { animation-duration: 1s; animation-fill-mode: both; animation-name: fadeRoute; } @keyframes fadeRoute { from { opacity: 0; } to { opacity: 1; } }
cssTransition.less
@time: 300ms; /** * 页面转场动画 需要导入到 global.less 中 */ // 动画开始的时候 页面一定要定位住 不然页面组件的布局是上下布局 导致动画效果不显示 .main { position: fixed; top: 0; width: 100vw; min-height: 100vh; background: white; } //前进进入 .forward-enter { &:extend(.main); opacity: 1; transform: translateX(100%); } //前进进入中 .forward-enter-active { &:extend(.main); opacity: 1; transform: translateX(0); transition: all @time ease-in; z-index: 999; } //前进退出 .forward-exit { &:extend(.main); opacity: 1; transform: translateX(0); } //前进退出中 .forward-exit-active { &:extend(.main); opacity: 1; transform: translateX(-100%); transition: all @time ease-in; } //后退进入 .back-enter { &:extend(.main); opacity: 1; transform: translateX(-100%); } //后退进入中 .back-enter-active { &:extend(.main); opacity: 1; transform: translateX(0); transition: all @time ease-in; z-index: 999; } //后退退出 .back-exit { &:extend(.main); opacity: 1; transform: translateX(0); } //后退退出中 .back-exit-active { &:extend(.main); opacity: 1; transform: translate(100%); transition: all @time ease-in; }
博客园作者:herry菌朋友,看到这里,关注作者的公众号吧,不漏掉更新哦
![]()