1. 程式人生 > 其它 >react-transition-group配合css透明度變化,實現頁面順滑跳轉。

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;
}

朋友,看到這裡,用支付寶掃碼領個紅包吧!實體店付款可以優惠哦!

請認準【http://wuhairui.cnblogs.com/】