我已经阅读了整个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。
任何人都可以帮助解决这个问题吗?
网上没有太多解释,谢谢!