下载插件
npm i react-transition-group
配置路由
import { createBrowserRouter as ReactRouter,Navigate } from "react-router-dom";import App from '../App.js'
import Login from "../view/login.js";
import Home from "../home.js";
const router = ReactRouter([{path:"/",element:<App />,children:[{path:'/login',element:<Login />},{path:"/home",element:<Home />}]},])export default router
app组件中引入并使用
import React from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import router from './router';
import { Outlet } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
import './aa.scss'
const App = () => {return (<div><TransitionGroup className='transition_wrapper' style={{ width: "100%", height: "100%" }}><CSSTransition key={useLocation().pathname} unmountOnExit timeout={2000} classNames='animate'><Outlet></Outlet></CSSTransition></TransitionGroup></div>);
}export default App;
引入动画样式
/* 入场动画过程 */
.animate-enter{opacity: 0;transform: translateX(100%);}.animate-enter-active{transition: 2s;opacity: 1;transform: translateX(0px);}.animate-enter-done{opacity: 1;transform: translateX(0px);}/* 出场动画过程 */.animate-exit{opacity: 1;transform: translateX(0);}.animate-exit-active{transition: 0s;opacity: 0;transform: translateX(-100%);}.animate-exit-done{opacity: 0;transform: translateX(-100%);}
实现效果