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

Reactjs 如何使用react spring按顺序执行两个动画?,reactjs,react-spring,Reactjs,React Spring,我尝试链接两个弹簧(使用useChain),这样一个弹簧只能在另一个弹簧完成后启动,但它们同时被设置动画。我做错了什么 import React,{useRef,useState}来自“React” 从'react dom'导入{render} 从“react spring”导入{useSpring,动画,useChain} 函数App(){ 常量[计数器,设置计数器]=使用状态(0) const topRef=useRef() const leftRef=useRef() const{top}

我尝试链接两个弹簧(使用
useChain
),这样一个弹簧只能在另一个弹簧完成后启动,但它们同时被设置动画。我做错了什么

import React,{useRef,useState}来自“React”
从'react dom'导入{render}
从“react spring”导入{useSpring,动画,useChain}
函数App(){
常量[计数器,设置计数器]=使用状态(0)
const topRef=useRef()
const leftRef=useRef()
const{top}=useSpring({top:(window.innerHeight*counter)/10,ref:topRef})
const{left}=useSpring({left:(window.innerWidth*计数器)/10,ref:leftRef})
useChain([topRef,leftRef])
返回(
设置计数器((计数器+1)%10)}>
点击我!

我做了一些挖掘工作,因为这也让我感到困惑,并被发现

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

我已经测试过了,它似乎可以做到:

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

useChain([topCurrent, leftCurrent]);

它强制链每次引用ref的当前值。turnary在其中,因为挂载上ref的值是未定义的。
-可能有一种更优雅的方法来解释这一点。

我刚刚发现有一个更简单的解决方案,只需使用
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>
  )
}
函数应用程序(){
常量[计数器,设置计数器]=使用状态(0)
const style=useSpring({
致:[
{top:(window.innerHeight*计数器)/5},
{左:(window.innerWidth*计数器)/5}
]
})
返回(
设置计数器((计数器+1)%5)}>
点击我!

显然,仅在其中一个引用中使用此解决方案就足够了。我甚至尝试添加第三个spring,但它仍然有效: