react 实现效果
React 实现动画效果的方法
使用 CSS 过渡动画 在 React 组件中通过 className 或 style 属性直接应用 CSS 过渡效果。定义 CSS 关键帧或过渡属性,通过状态变化触发动画。
.fade-in {
animation: fadeIn 0.5s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
function AnimatedComponent() {
const [isVisible, setIsVisible] = useState(false);
return (
<div className={isVisible ? 'fade-in' : ''}>
<button onClick={() => setIsVisible(!isVisible)}>
Toggle Animation
</button>
</div>
);
}
使用 React Transition Group 该库提供组件用于管理组件的装载和卸载动画,适合列表项或路由切换动画场景。
import { CSSTransition } from 'react-transition-group';
function App() {
const [inProp, setInProp] = useState(false);
return (
<div>
<CSSTransition
in={inProp}
timeout={300}
classNames="fade"
unmountOnExit
>
<div>Animated Content</div>
</CSSTransition>
<button onClick={() => setInProp(!inProp)}>
Toggle
</button>
</div>
);
}
使用 Framer Motion 专业级动画库提供声明式 API,支持复杂动画序列和手势交互。
import { motion } from 'framer-motion';
function Box() {
return (
<motion.div
animate={{
x: 100,
rotate: 90,
}}
transition={{ duration: 0.5 }}
>
Animated Box
</motion.div>
);
}
使用 React Spring 基于物理模型的动画库,适合需要自然运动效果的项目,支持弹簧物理特性配置。
import { useSpring, animated } from 'react-spring';
function SpringDemo() {
const props = useSpring({
opacity: 1,
from: { opacity: 0 },
config: { duration: 1000 }
});
return <animated.div style={props}>Fade In</animated.div>;
}
使用 GSAP 集成 通过 ref 获取 DOM 节点后使用 GSAP 的强大时间线控制能力。
import { useRef, useEffect } from 'react';
import gsap from 'gsap';
function GsapDemo() {
const boxRef = useRef();
useEffect(() => {
gsap.to(boxRef.current, {
x: 100,
duration: 1,
repeat: -1,
yoyo: true
});
}, []);
return <div ref={boxRef}>GSAP Animation</div>;
}
性能优化建议
减少重绘区域 使用 will-change CSS 属性标记动画元素,启用 GPU 加速。
.animated-element {
will-change: transform, opacity;
}
使用 React.memo 避免不必要的组件重新渲染影响动画流畅度。
const MemoizedComponent = React.memo(function MyComponent({ prop }) {
return <div>{prop}</div>;
});
懒加载动画库 通过动态导入减少初始包体积。
const LazyAnimation = React.lazy(() => import('./HeavyAnimationComponent'));
优先使用 transform 和 opacity 这些属性不会触发布局重排,性能开销小于修改 top/left 等属性。
.high-performance {
transform: translateX(100px);
opacity: 0.5;
}






