【问题标题】:How to execute two animations sequentially, using react-spring?如何使用react-spring顺序执行两个动画?
【发布时间】:2020-07-23 18:03:13
【问题描述】:

我尝试链接两个弹簧(使用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

【问题讨论】:

    标签: reactjs react-spring


    【解决方案1】:

    我刚刚发现有一个更简单的解决方案,只使用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

    【讨论】:

      【解决方案2】:

      我进行了一些挖掘,因为这也让我感到困惑,并遇到了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 在那里,因为 mount 上 ref 的值是 undefined - 可能有更优雅的方式来解释这一点。

      【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2020-10-07
      • 2015-12-17
      • 1970-01-01
      相关资源
      最近更新 更多