react如何实现特效
React 实现特效的常见方法
使用 CSS 动画或过渡
通过 CSS 的 @keyframes 或 transition 属性创建动画效果,结合 React 的状态管理控制动画触发时机。适合简单 hover、淡入淡出等基础特效。
import React, { useState } from 'react';
import './styles.css';
function FadeInBox() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>Toggle</button>
<div className={`box ${isVisible ? 'fade-in' : ''}`}></div>
</div>
);
}
CSS 文件示例:
.box {
width: 100px;
height: 100px;
background: blue;
opacity: 0;
transition: opacity 0.5s ease;
}
.fade-in {
opacity: 1;
}
使用动画库(如 Framer Motion)
Framer Motion 提供声明式 API 实现复杂动画,支持手势驱动、布局动画等高级特性。适合需要物理效果或复杂交互的场景。

import { motion } from 'framer-motion';
function DragableCircle() {
return (
<motion.div
drag
dragConstraints={{ left: 0, right: 100, top: 0, bottom: 100 }}
whileHover={{ scale: 1.2 }}
whileTap={{ scale: 0.8 }}
style={{ width: 50, height: 50, background: 'red' }}
/>
);
}
使用 React Spring 实现物理动画
React Spring 基于弹簧物理模型,适合需要自然运动效果(如弹性、缓动)的场景。支持数值、滚动、轨迹等多种动画类型。
import { useSpring, animated } from 'react-spring';
function BouncingBall() {
const props = useSpring({
from: { y: 0 },
to: async (next) => {
while (true) {
await next({ y: 100 });
await next({ y: 0 });
}
},
config: { tension: 200, friction: 10 }
});
return (
<animated.div
style={{
width: 50,
height: 50,
background: 'green',
borderRadius: '50%',
...props
}}
/>
);
}
结合 SVG 和 GSAP
对于路径动画、复杂矢量图形特效,可使用 GSAP 库与 React 的 ref 系统配合操作 SVG 元素。

import React, { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
function SvgWave() {
const pathRef = useRef(null);
useEffect(() => {
gsap.to(pathRef.current, {
duration: 2,
attr: { d: "M0 100 Q50 200 100 100 T200 100" },
repeat: -1,
yoyo: true
});
}, []);
return (
<svg width="200" height="200">
<path
ref={pathRef}
d="M0 100 Q50 0 100 100 T200 100"
fill="none"
stroke="purple"
/>
</svg>
);
}
视差滚动特效
通过监听滚动事件或使用库(如 react-scroll-parallax)实现多层背景的视差效果,增强页面立体感。
import { ParallaxProvider, ParallaxBanner } from 'react-scroll-parallax';
function ParallaxScene() {
return (
<ParallaxProvider>
<ParallaxBanner
layers={[
{ image: 'background.jpg', speed: -20 },
{ image: 'foreground.png', speed: -10 }
]}
style={{ height: '500px' }}
/>
</ParallaxProvider>
);
}
粒子系统(如 react-tsparticles)
对于火焰、烟雾、星空等动态粒子效果,可使用专用粒子库快速实现。
import Particles from 'react-tsparticles';
function StarField() {
return (
<Particles
options={{
particles: {
number: { value: 100 },
move: { enable: true, speed: 1 },
size: { value: 3 }
}
}}
/>
);
}
性能优化建议
- 使用
will-changeCSS 属性提示浏览器优化 - 对复杂动画启用硬件加速(如
transform: translateZ(0)) - 避免频繁触发重排的属性(如
width/height) - 使用
React.memo防止不必要的组件重渲染 - 动画结束后清理未完成的动画帧(
cancelAnimationFrame)






