react怎么实现动画
React 动画实现方法
使用 CSS 过渡和动画
在 React 中可以直接通过 CSS 的 transition 或 animation 属性实现动画效果。通过状态变化触发类名切换,配合 CSS 定义动画过程。
import React, { useState } from 'react';
import './styles.css';
function App() {
const [isActive, setIsActive] = useState(false);
return (
<div>
<button onClick={() => setIsActive(!isActive)}>
Toggle Animation
</button>
<div className={`box ${isActive ? 'active' : ''}`} />
</div>
);
}
.box {
width: 100px;
height: 100px;
background: red;
transition: all 0.5s ease;
}
.box.active {
transform: translateX(100px);
background: blue;
}
使用 React Transition Group
React Transition Group 是一个官方推荐的动画库,提供组件管理元素的进入和离开动画。
import { CSSTransition } from 'react-transition-group';
function Fade({ in: inProp }) {
return (
<CSSTransition
in={inProp}
timeout={300}
classNames="fade"
unmountOnExit
>
<div>Fade Animation</div>
</CSSTransition>
);
}
.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 是一个流行的 React 动画库,提供声明式的 API 和丰富的动画功能。
import { motion } from 'framer-motion';
function App() {
return (
<motion.div
animate={{ x: 100 }}
transition={{ duration: 0.5 }}
>
Animated Element
</motion.div>
);
}
使用 React Spring
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>;
}
使用 GreenSock (GSAP)
GSAP 是一个强大的 JavaScript 动画库,可以在 React 中使用。
import { useRef, useEffect } from 'react';
import gsap from 'gsap';
function App() {
const boxRef = useRef();
useEffect(() => {
gsap.to(boxRef.current, {
duration: 1,
x: 100,
rotation: 360,
ease: "bounce.out"
});
}, []);
return <div ref={boxRef}>GSAP Animation</div>;
}
性能优化技巧
对于需要高性能的动画,考虑使用 will-change CSS 属性或 transform 和 opacity 属性,这些属性可以利用硬件加速。
.animated-element {
will-change: transform, opacity;
}
避免在动画过程中触发重排操作,尽量使用 transform 和 opacity 进行动画。对于列表动画,使用 React.Fragment 或专门的列表动画库如 react-flip-toolkit。







