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

react-spring中useSprings设置逐字符动画延迟不生效如何解决

问题原因

react-spring的delay属性接收毫秒为单位的数值,你当前设置的delay: (0.5 + i / 10)计算结果最大仅为3ms左右,延迟差别人眼完全无法识别,因此看起来所有字符同时启动动画。
另外你要实现从右向左的弹跳顺序,当前正序索引计算延迟的逻辑是从左到右入场,和预期方向相反。

修复方案
  • 将delay数值调整为毫秒级,按逐字符动画的常规视觉节奏,单字符间隔设置为30~80ms效果最佳
  • 倒序计算延迟值,让位置更靠右(索引更大)的字符延迟更小,优先启动动画
  • 给动画字符span添加display: inline-block样式,避免inline元素对transform属性兼容问题导致动画异常;可给标题元素添加overflow: hidden样式,避免大偏移量的初始translateX触发页面横向滚动条
修正后代码
import React from "react";
import { useSprings, animated } from "react-spring"
import s from '../../styles/pages/home.module.scss'


// 逐字符拆分文本,包含空格
let textString = "Random text for this example."
let textArray = Array.from(textString)

const HeroText = () => {

  const springs = useSprings(
    textArray.length,
    textArray.map((item, i)=> ({
     id : i,
     from : {opacity: 0, translateX : '100px'}, // 初始偏移量无需设置过大,避免触发横向滚动
     to: {opacity: 1, translateX : '0px'},
     // 倒序计算延迟:最右侧字符延迟0,每个靠左的字符多等50ms,实现从右向左依次入场
     delay: (textArray.length - i) * 50,
     config: { mass: 4, tension: 200, friction: 30}
    }))  
  )

  let elements = springs.map((spring, i) => {
    return(
     <animated.span key={i} style={{...spring, display: 'inline-block'}}>
      {textArray[i] === ' ' ? <span>&nbsp;</span> : textArray[i]}
     </animated.span>
    )
  })


  return(
    <div className={s.heroText}>
     <h1 className="my-heading divided-heading" style={{display: 'inline-block', overflow: 'hidden'}}>
       {elements}
     </h1>
    </div>
  )
}

export default HeroText

内容的提问来源于stack exchange,提问作者Stephane-Gon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:03:23