react如何衰减
在 React 中实现动画衰减效果
动画衰减(Decay Animation)是一种常见的交互效果,模拟物理世界中的摩擦力逐渐减速运动。在 React 中可以通过以下方式实现:
使用 react-spring 库
react-spring 是一个流行的动画库,内置支持衰减动画:

import { useSpring, animated } from 'react-spring'
function DecayDemo() {
const [props, set] = useSpring(() => ({
x: 0,
deceleration: 0.998,
onRest: () => console.log('animation stopped')
}))
return (
<animated.div
style={{
transform: props.x.to(x => `translateX(${x}px)`),
width: 100,
height: 100,
background: 'blue'
}}
onMouseDown={e => {
set({ x: e.clientX, immediate: true })
}}
onMouseMove={e => {
if (e.buttons) {
set({ x: e.clientX })
}
}}
/>
)
}
使用 framer-motion 库
framer-motion 也提供衰减动画支持:

import { motion } from 'framer-motion'
function DecayBox() {
return (
<motion.div
drag
dragConstraints={{ left: 0, right: 0 }}
dragElastic={0.5}
dragMomentum={true}
style={{
width: 100,
height: 100,
background: 'red'
}}
/>
)
}
手动实现衰减动画
对于自定义需求,可以手动实现衰减算法:
import { useState, useEffect, useRef } from 'react'
function ManualDecay() {
const [position, setPosition] = useState(0)
const velocityRef = useRef(0)
const animationRef = useRef(null)
const startDecay = (initialVelocity) => {
velocityRef.current = initialVelocity
const deceleration = 0.95
const animate = () => {
if (Math.abs(velocityRef.current) < 0.1) {
cancelAnimationFrame(animationRef.current)
return
}
setPosition(prev => prev + velocityRef.current)
velocityRef.current *= deceleration
animationRef.current = requestAnimationFrame(animate)
}
animationRef.current = requestAnimationFrame(animate)
}
return (
<div
style={{
transform: `translateX(${position}px)`,
width: 100,
height: 100,
background: 'green'
}}
onClick={() => startDecay(30)}
/>
)
}
性能优化注意事项
使用 will-change 属性提示浏览器优化动画性能:
<div style={{ willChange: 'transform' }} />
避免在动画期间触发重排操作,尽量只修改 transform 和 opacity 属性。对于复杂场景,考虑使用 React 的 useMemo 和 useCallback 减少不必要的渲染。






