【发布时间】:2019-12-31 11:47:22
【问题描述】:
我已经阅读了整个 react-spring 文档,但似乎没有明确的方法来做到这一点。
我的尝试:
import React, { useRef, useState } from "react"
import { animated, useSpring } from "react-spring"
const App = () => {
const scrollDestinationRef = useRef()
const [elementScroll, setElementScroll] = useState(false)
const buttonClickHandler = () => setElementScroll(prevState => !prevState)
const scrollAnimation = useSpring({
scroll: elementScroll
? scrollDestinationRef.current.getBoundingClientRect().top
: 0
})
return (
<main>
{/* Click to scroll to destination */}
<animated.button
onClick={buttonClickHandler}
scrollTop={scrollAnimation.scroll}
style={{
height: "1000px",
width: "100%",
backgroundColor: "tomato"
}}
>
Scroll to destination
</animated.button>
{/* Scroll destination */}
<div
ref={scrollDestinationRef}
style={{
height: "200px",
width: "200px",
backgroundColor: "green"
}}
></div>
</main>
)
}
export default App
我正在尝试使用 ref 和 hooks。
useRef 附加到滚动目的地,以便找到它与网站天花板的偏移顶部。
我使用useState 在点击状态之间切换以触发滚动。
我使用useSpring 触发从0 到滚动目标的滚动顶部的动画,也就是getBoundingClientRect().top。
谁能帮忙解决这个问题?
网上解释不多,谢谢!
【问题讨论】:
标签: javascript reactjs react-spring