gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:04:21 24 4
gpt4 key购买 nike

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

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'))

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

最佳答案

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

关于reactjs - 如何使用react-spring顺序执行两个动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61149605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com