【React】基于react-transition-group实现转场切换路由跳转动画

一、效果演示

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%);
}<
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值