如何在react-spring中实现hover触发的多步骤链式旋转动画
解决方案
你可以直接通过useSpring的to参数做条件分支,当isBooped为true时返回多步动画数组,为false时直接归位到0度即可,不需要额外拆分多个状态控制,完整修改后的代码如下:
import { useState, useCallback } from 'react'; import { useSpring, config } from '@react-spring/web'; const BoopIcon = () => { const [isBooped, setBooped] = useState(false); const style = useSpring({ rotate: isBooped ? undefined : 0, to: isBooped ? [ { rotate: 10 }, { rotate: -10 }, { rotate: 0 } ] : undefined, config: config.wobbly, onRest: () => { // 所有动画执行完毕后自动重置状态 if (isBooped) setBooped(false); } }); const onMouseEnter = useCallback(() => { // 避免动画未跑完时重复触发导致错乱 if (!isBooped) setBooped(true); }, [isBooped]); return ( <Button onMouseEnter={onMouseEnter}> <Icon style={style} /> </Button> ); };
- 多步动画会严格按照你传入数组的顺序依次执行,正好匹配「10deg → -10deg → 0deg」的摆动需求
- 用
onRest回调自动重置状态,不需要手动设置定时器,适配不同动画配置的时长 - 增加了触发前的状态判断,避免用户连续hover时动画逻辑冲突
内容的提问来源于stack exchange,提问作者Nihil
相关产品推荐
相关产品推荐

