react如何衰减
React 中的动画衰减效果
在 React 中实现动画衰减效果(如弹簧动画或缓动动画)可以通过以下方式实现:
使用 react-spring 库:
import { useSpring, animated } from 'react-spring'
function Fade() {
const props = useSpring({
from: { opacity: 0 },
to: { opacity: 1 },
config: { mass: 1, tension: 180, friction: 12 }
})
return <animated.div style={props}>I will fade in</animated.div>
}
CSS 过渡实现衰减
通过 CSS 的 transition-timing-function 属性实现缓动效果:
.box {
transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
使用 Framer Motion 库
Framer Motion 提供更简单的衰减动画 API:
import { motion } from 'framer-motion'
<motion.div
animate={{ x: 100 }}
transition={{ type: "spring", damping: 10 }}
/>
自定义 JavaScript 实现
通过 requestAnimationFrame 实现自定义衰减动画:
function animateDecay(start, velocity, callback) {
let position = start
const decay = 0.9
const tick = () => {
position += velocity
velocity *= decay
callback(position)
if (Math.abs(velocity) > 0.5) {
requestAnimationFrame(tick)
}
}
tick()
}
性能优化建议
对于复杂动画场景,优先使用 CSS 硬件加速属性如 transform 和 opacity。避免在动画过程中触发重排操作,使用 will-change 属性提示浏览器优化。







