如何使用react-spring顺序执行两个动画?

How to execute two animations sequentially, using react-spring?

我尝试链接两个弹簧(使用 useChain),这样一个弹簧只在另一个弹簧结束后才开始,但它们是同时进行动画处理的。我做错了什么?

import React, { useRef, useState } from 'react'
import { render } from 'react-dom'
import { useSpring, animated, useChain } from 'react-spring'

function App() {
  const [counter, setCounter] = useState(0)
  const topRef = useRef()
  const leftRef = useRef()
  const { top } = useSpring({ top: (window.innerHeight * counter) / 10, ref: topRef })
  const { left } = useSpring({ left: (window.innerWidth * counter) / 10, ref: leftRef })

  useChain([topRef, leftRef])

  return (
    <div id="main" onClick={() => setCounter((counter + 1) % 10)}>
      Click me!
      <animated.div id="movingDiv" style={{ top, left }} />
    </div>
  )
}

render(<App />, document.getElementById('root'))

这是一个演示问题的代码框: https://codesandbox.io/s/react-spring-usespring-hook-m4w4t

我做了一些挖掘,因为这也让我感到困惑并遇到了 this spectrum chat

我不确定我是否完全理解发生了什么,但您代码中 refs 的 current 值似乎只被读取一次,因此当组件安装时,链会立即完成并且永不重置。如果您为两个弹簧输入硬编码值,然后使用转向器控制它们,您的代码确实有效,但显然您正在寻找动态解决方案。

我已经测试过了,它似乎可以完成工作:

const topCurrent = !topRef.current ? topRef : {current: topRef.current};
const leftCurrent = !leftRef.current ? leftRef : {current: leftRef.current};

useChain([topCurrent, leftCurrent]);

强制链每次引用ref的当前值。 turnary 在那里,因为 ref on mount 的值是 undefined - 可能有更优雅的方式来解释这个。

我刚刚发现有一个更简单的解决方案,只使用 useSpring:

function App() {
  const [counter, setCounter] = useState(0)

  const style = useSpring({
    to: [
      { top: (window.innerHeight * counter) / 5 },
      { left: (window.innerWidth * counter) / 5 }
    ]
  })

  return (
    <div id="main" onClick={() => setCounter((counter + 1) % 5)}>
      Click me!
      <animated.div id="movingDiv" style={style} />
    </div>
  )
}

示例:https://codesandbox.io/s/react-spring-chained-animations-8ibpi