React-spring 如何正确地为数组的字母设置动画

React-spring how to animate letters of an array correctly

在这段带有 react-spring 的代码中,我得到了一个动画,其中每个字母都等到前一个动画结束,同时它也在动画中

为什么会发生这种情况,我该如何解决?

  const text = [...'hey there how are you']
  const from = { transform: 'rotateX(0deg) translateY(0px) rotate(0deg) scale(1)' }
  const to = inView
    ? [
        { transform: 'rotateX(30deg) translateY(10px) rotate(-13deg) scale(1)' },
        { transform: 'rotateX(0deg) translateY(-22px) rotate(3deg) scale(1.1)' },
        { ...from },
      ]
    : from

  const trail = useTrail(text.length, {
    config: { mass: 5, tension: 2000, friction: 200 },
    from: from,
    to: to,
  })

  return (
    <>
      <Div ref={handleRef}>
        {trail.map((props, i) => (
          <animated.span key={`char${i}`} style={props}>
            {text[i] === ' ' ? <>&nbsp;</> : text[i]}
          </animated.span>
        ))}
      </Div>
    </>
  )

使用useSprings我可以获得每个项目的独立字符串,我可以单独延迟

to: 只有一个规则时,这是开箱即用的,但如果您想连接更多规则,那么每个元素都不会独立于其他元素

使用useSprings你可以获得这种个性

const text = [...'hey there how are you']
  const from = { transform: 'translate3d(0,0px,0)' }
  const to = inView ? [{ transform: 'translate3d(0,-40px,0)' }, { transform: 'translate3d(0,40px,0)' }] : from

  const base = {
    config: { mass: 5, tension: 2000, friction: 200 },
    from: from,
    to: to,
  }

  const springs = useSprings(text.length, text.map((t, i) => ({ ...base, delay: 100 * i })))

  return (
    <Div ref={handleRef}>
      {springs.map((s, i) => {
        return (
          <animated.span key={`char${i}`} style={s}>
            {text[i] === ' ' ? <>&nbsp;</> : text[i]}
          </animated.span>
        )
      })}
    </Div>
  )