react.js如何实现动画
使用 CSS 过渡和动画
在 React 中可以通过 CSS 的 transition 或 @keyframes 动画实现简单的动画效果。通过动态修改组件的 className 或内联样式触发动画。
import React, { useState } from 'react';
import './styles.css';
function App() {
const [isActive, setIsActive] = useState(false);
return (
<div
className={`box ${isActive ? 'active' : ''}`}
onClick={() => setIsActive(!isActive)}
>
Click me
</div>
);
}
对应的 CSS 文件:
.box {
width: 100px;
height: 100px;
background: blue;
transition: all 0.3s ease;
}
.box.active {
transform: scale(1.2);
background: red;
}
使用 React Transition Group
react-transition-group 是一个流行的库,用于管理组件的进入和退出动画。适用于列表增减、模态框等场景。
安装:
npm install react-transition-group
示例:
import { CSSTransition } from 'react-transition-group';
function App() {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(!show)}>Toggle</button>
<CSSTransition
in={show}
timeout={300}
classNames="fade"
unmountOnExit
>
<div className="alert">Hello!</div>
</CSSTransition>
</div>
);
}
CSS:
.fade-enter {
opacity: 0;
}
.fade-enter-active {
opacity: 1;
transition: opacity 300ms;
}
.fade-exit {
opacity: 1;
}
.fade-exit-active {
opacity: 0;
transition: opacity 300ms;
}
使用 Framer Motion
framer-motion 是一个功能强大的动画库,支持复杂的动画效果和手势交互。

安装:
npm install framer-motion
示例:
import { motion } from 'framer-motion';
function App() {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 1 }}
whileHover={{ scale: 1.1 }}
>
Animated Element
</motion.div>
);
}
使用 React Spring
react-spring 是一个基于物理的动画库,适合实现自然流畅的动画效果。
安装:

npm install react-spring
示例:
import { useSpring, animated } from 'react-spring';
function App() {
const props = useSpring({
opacity: 1,
from: { opacity: 0 },
config: { duration: 1000 },
});
return <animated.div style={props}>Fade In</animated.div>;
}
使用 GSAP
GSAP 是一个高性能的 JavaScript 动画库,适合复杂的时间轴动画。
安装:
npm install gsap
示例:
import React, { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
function App() {
const boxRef = useRef();
useEffect(() => {
gsap.to(boxRef.current, {
x: 100,
rotation: 360,
duration: 2
});
}, []);
return <div ref={boxRef}>GSAP Animation</div>;
}
性能优化建议
- 使用
will-change或transform属性提升动画性能。 - 避免频繁触发重排(如修改
width、height),优先使用transform和opacity。 - 对于复杂动画,使用
requestAnimationFrame或专用动画库(如 GSAP、Framer Motion)。






