You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为useSpring的双向动画设置不同执行时长?

为useSpring双向动画配置不同时长的实现方法

useSpring的config参数并非只能写固定值,可以直接根据控制显隐的状态变量动态切换配置,就能实现两个方向动画的差异化时长。

  • 当show为true时,对应组件从隐藏到展示的动画(from -> to),配置时长为300ms
  • 当show为false时,对应组件从展示到隐藏的动画(to -> from),配置时长为100ms

核心实现代码如下:

const animationStyle = useSpring({
  bottom: show ? 0 : -71,
  from: {
    bottom: -71
  },
  // 按动画方向动态返回对应配置
  config: show 
    ? { duration: 300 } // 鼠标移入展示:耗时0.3s
    : { duration: 100 } // 鼠标移出隐藏:耗时0.1s
})

如果需要优化动画手感,还可以给两个方向搭配不同的缓动函数,示例:

import { easings } from '@react-spring/web'

const animationStyle = useSpring({
  bottom: show ? 0 : -71,
  from: { bottom: -71 },
  config: show 
    ? { duration: 300, easing: easings.easeOutCubic } // 展示时缓出,更柔和
    ? { duration: 100, easing: easings.easeInQuad } // 隐藏时快速收起,更利落
})

注意:from参数固定为组件初始隐藏的状态值即可,不需要随show动态修改,react-spring会自动从当前动画值过渡到目标值,不会出现跳回初始位置的问题。

内容的提问来源于stack exchange,提问作者wu bevis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 09:36:26