react如何添加效果
在React中添加效果的方法
使用CSS动画或过渡
通过CSS的transition或animation属性实现简单效果。在React中直接通过className或style属性应用CSS。
.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库提供了组件化的过渡效果管理,适合复杂的入场/离场动画。

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>
</>
);
}
使用Framer Motion
Framer Motion是专为React设计的高性能动画库,支持手势和复杂动画序列。

import { motion } from 'framer-motion';
function DragComponent() {
return (
<motion.div
drag
dragConstraints={{ left: 0, right: 0, top: 0, bottom: 0 }}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
可拖拽元素
</motion.div>
);
}
使用useEffect钩子实现滚动效果
通过useEffect和window事件监听实现滚动触发效果。
function ScrollComponent() {
const [scrolled, setScrolled] = useState(false);
useEffect(() => {
const handleScroll = () => {
setScrolled(window.scrollY > 100);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div className={scrolled ? 'scrolled' : ''}>滚动时变化</div>;
}
使用GreenSock(GSAP)动画库
GSAP提供专业级的动画控制能力,适合需要精确时间控制的复杂动画。
import { useRef, useEffect } from 'react';
import gsap from 'gsap';
function GSAPComponent() {
const boxRef = useRef();
useEffect(() => {
gsap.to(boxRef.current, {
duration: 1,
x: 100,
rotation: 360,
ease: 'bounce.out'
});
}, []);
return <div ref={boxRef}>GSAP动画元素</div>;
}
每种方法适用于不同场景:CSS方案适合简单UI效果,React Transition Group适合组件过渡,Framer Motion适合交互丰富的动画,GSAP适合复杂时间轴动画。根据项目需求选择合适的技术方案。






