Umi实现路由动画
1、首先在src目录下建一个layouts文件夹
layouts目录下创建两个文件 index.tsx和index.less
index.tsx文件下代码:
import React, { useState, useEffect } from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { history as Router, withRouter } from 'umi'
import { Switch } from 'react-router'
import './index.less'
const routerType = {
'POP': 'back',
'PUSH': 'in',
'REPLACE': 'in'
}
export default withRouter(({ location, children, history }) => {
return (
<div>
<TransitionGroup style={{ height: '100%' }} className='transition_wrapper' childFactory={(child) => (
React.cloneElement(child, { classNames: routerType[history.action] })
)}>
<CSSTransition key={location.pathname} appear timeout={3000}>
<Switch location={location}>{(children as any)?.props?.children}</Switch>
</CSSTransition>
</TransitionGroup>
</div>
)
})
index.less文件下代码:
.in-enter-active {
// 入场的过渡状态类
transition: all 3s;
transform: translate(0, 0) !important;
}
.in-enter-done {
// 入场的动画的结束状态类
// opacity: 0.5;
transform: translate(0, 0) !important;
}
.in-enter {
// 入场的动画开始状态类
z-index: 5 !important;
transform: translate(100%, 0);
}
.in-exit-active {
// 离场动画
opacity: 0;
transition: all 3s;
transform: translate(-100%, 0) !important;
}
.in-exit {
// 离场动画开始
// transform: translate(0, 0)!important;
}
.in-exit-done {
// 离场动画结束
}
// 返回动画
.back-enter-active {
// 入场的过渡状态类
transition: all 3s;
transform: translate(0, 0) !important;
}
.back-enter-done {
// 入场的动画的结束状态类
opacity: 0.5;
transform: translate(0, 0);
}
.back-enter {
// 入场的动画开始状态类
z-index: 5 !important;
transform: translate(-100%, 0);
}
.back-exit-active {
// 离场动画
opacity: 0;
transition: all 3s;
transform: translate(100%, 0) !important;
}
.back-exit {
// 离场动画开始
// transform: translate(0, 0)!important;
}
.back-exit-done {
// 离场动画结束
}
2、在pages下创建两个文件夹
Par/index.tsx 代码
<div onClick={() => { history.push('/sun') }} style={{ width: '100%', height: '100%', background: 'green' }}>
<h1>第一个页面</h1>
</div>
Sun/index.tsx 代码
<div onClick={() => { history.push('/par') }} style={{ width: '100%', height: '100%', background: 'green' }}>
<h1>第二个页面</h1>
</div>
3、路由配置
routes: [
{
path: '/', component: '@/layouts/index.tsx',
routes: [
{ path: '/par', component: '@/pages/Par'},
{ path: '/sun', component: '@/pages/Sun'},
]
}
],