react如何添加效果
React 添加动画效果的方法
使用 CSS 过渡动画 在 React 组件中直接通过 className 或 style 属性应用 CSS 过渡效果。定义 CSS 类包含 transition 属性,通过状态变化触发动画。
.fade-in {
opacity: 0;
transition: opacity 0.5s ease-in;
}
.fade-in.active {
opacity: 1;
}
function FadeInComponent() {
const [isActive, setIsActive] = useState(false);
return (
<div
className={`fade-in ${isActive ? 'active' : ''}`}
onClick={() => setIsActive(true)}
>
点击淡入
</div>
);
}
使用 React Transition Group
React Transition Group 提供组件帮助管理组件的进入和离开动画。安装库后使用 CSSTransition 组件包裹需要动画的元素。
npm install react-transition-group
import { CSSTransition } from 'react-transition-group';
function ToggleComponent() {
const [show, setShow] = useState(false);
return (
<>
<button onClick={() => setShow(!show)}>切换</button>
<CSSTransition
in={show}
timeout={300}
classNames="fade"
unmountOnExit
>
<div>会淡入淡出的内容</div>
</CSSTransition>
</>
);
}
对应的 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 提供声明式 API 创建复杂动画。安装后通过 motion 组件和动画属性实现效果。
npm install framer-motion
import { motion } from 'framer-motion';
function AnimatedBox() {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
可交互动画元素
</motion.div>
);
}
使用 React Spring 物理动画
React Spring 基于物理规则创建更自然的动画效果,适合需要弹簧物理特性的场景。
npm install 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}>渐显内容</animated.div>;
}
使用 GSAP 高级动画
GSAP 提供专业级动画控制,适合需要复杂时间轴和精确控制的场景。
npm install gsap
import { useRef, useEffect } from 'react';
import gsap from 'gsap';
function GsapDemo() {
const boxRef = useRef();
useEffect(() => {
gsap.to(boxRef.current, {
duration: 1,
x: 100,
rotation: 360,
ease: "bounce.out"
});
}, []);
return <div ref={boxRef}>GSAP 动画元素</div>;
}






