react实现入场动画
React 实现入场动画的方法
使用 CSS Transition 实现基础动画
在 React 组件中通过添加 CSS 类名触发动画效果。定义一个包含过渡属性的 CSS 类,通过组件状态或 props 控制类名的添加与移除。
.fade-enter {
opacity: 0;
}
.fade-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
function FadeComponent({ in: inProp }) {
const [show, setShow] = useState(inProp);
return (
<CSSTransition
in={show}
timeout={500}
classNames="fade"
unmountOnExit
>
<div>Content with fade animation</div>
</CSSTransition>
);
}
利用 React Transition Group 库
React Transition Group 提供组件化方式管理动画生命周期,适合复杂入场动画场景。安装后使用 CSSTransition 或 Transition 组件。
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="alert"
unmountOnExit
>
<div className="alert">
Animated content
</div>
</CSSTransition>
</div>
);
}
使用 Framer Motion 实现高级动画
Framer Motion 提供声明式动画 API,支持复杂动画序列和手势交互。定义 motion 组件并设置初始/动画状态。
npm install framer-motion
import { motion } from 'framer-motion';
function AnimatedBox() {
return (
<motion.div
initial={{ opacity: 0, y: -50 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
Content with motion
</motion.div>
);
}
结合 useRef 和 useEffect 手动控制
通过 React 的 Hooks 直接操作 DOM 实现精细控制,适合需要自定义动画逻辑的场景。
function ManualAnimation() {
const ref = useRef(null);
useEffect(() => {
const node = ref.current;
node.style.transform = 'translateY(0)';
node.style.opacity = '1';
node.style.transition = 'all 0.3s ease';
return () => {
node.style.transform = 'translateY(-20px)';
node.style.opacity = '0';
};
}, []);
return (
<div
ref={ref}
style={{
transform: 'translateY(-20px)',
opacity: 0
}}
>
Manual animation content
</div>
);
}
基于 React Spring 的物理动画
React Spring 提供基于物理的动画效果,适合需要自然运动曲线的场景。使用 useSpring 或 animated 组件。
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}>Spring content</animated.div>;
}
每种方法适用于不同场景:CSS Transition 适合简单效果,React Transition Group 适合组件化动画管理,Framer Motion 适合复杂交互,手动控制适合定制需求,React Spring 适合物理动画效果。根据项目需求选择合适方案。







