react 实现页面切换动画
使用 React Router 和 CSS 过渡动画
在 React 中实现页面切换动画可以通过结合 React Router 和 CSS 过渡效果来完成。React Router 提供了路由切换的钩子,而 CSS 可以定义动画效果。
安装必要的依赖:
npm install react-router-dom
定义路由和动画组件:
import { Switch, Route, useLocation } from 'react-router-dom';
import { AnimatePresence, motion } from 'framer-motion';
function App() {
const location = useLocation();
return (
<AnimatePresence exitBeforeEnter>
<Switch location={location} key={location.pathname}>
<Route exact path="/">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<HomePage />
</motion.div>
</Route>
<Route path="/about">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<AboutPage />
</motion.div>
</Route>
</Switch>
</AnimatePresence>
);
}
使用 Framer Motion 库
Framer Motion 是一个专门为 React 设计的动画库,可以轻松实现复杂的页面过渡效果。
安装 Framer Motion:
npm install framer-motion
实现页面过渡:
import { motion } from 'framer-motion';
const PageTransition = ({ children }) => (
<motion.div
initial={{ x: 300, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: -300, opacity: 0 }}
transition={{ type: 'spring', stiffness: 100 }}
>
{children}
</motion.div>
);
function HomePage() {
return (
<PageTransition>
<h1>Home Page</h1>
</PageTransition>
);
}
使用 React Transition Group
React Transition Group 提供了组件进入和离开的过渡管理,适合需要更精细控制的场景。
安装 React Transition Group:
npm install react-transition-group
配置 CSS 过渡:
.page-enter {
opacity: 0;
transform: translateX(100%);
}
.page-enter-active {
opacity: 1;
transform: translateX(0);
transition: all 300ms ease-in;
}
.page-exit {
opacity: 1;
transform: translateX(0);
}
.page-exit-active {
opacity: 0;
transform: translateX(-100%);
transition: all 300ms ease-out;
}
实现组件:
import { CSSTransition, TransitionGroup } from 'react-transition-group';
function App() {
return (
<TransitionGroup>
<CSSTransition
key={location.key}
classNames="page"
timeout={300}
>
<Switch location={location}>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
</Switch>
</CSSTransition>
</TransitionGroup>
);
}
自定义 Hook 实现动画
对于需要更灵活控制的场景,可以创建自定义 Hook 来管理页面动画。
实现自定义 Hook:
import { useState, useEffect } from 'react';
function usePageAnimation() {
const [animate, setAnimate] = useState(false);
useEffect(() => {
setAnimate(true);
return () => setAnimate(false);
}, []);
return {
style: {
opacity: animate ? 1 : 0,
transform: animate ? 'translateY(0)' : 'translateY(20px)',
transition: 'all 0.3s ease'
}
};
}
function PageComponent() {
const animation = usePageAnimation();
return (
<div style={animation.style}>
<h1>Animated Page</h1>
</div>
);
}
性能优化建议
页面动画可能会影响性能,特别是在移动设备上。确保动画使用硬件加速,避免使用可能引起重排的属性。
优化 CSS:
.optimized-animation {
will-change: transform, opacity;
transform: translateZ(0);
backface-visibility: hidden;
perspective: 1000px;
}
限制动画复杂度,避免同时运行多个复杂动画。使用 requestAnimationFrame 替代 setTimeout 进行 JavaScript 动画。







