0

我正在尝试使用 React.js 和react-scroll来模拟Tesla的网络应用登陆页面滚动行为

滚动行为

假设我们有 2 个部分,主图是第 1 部分,并且在用户的一个小滚动中,触发了一个事件,它向下滚动到下一个部分(第 2 部分)

我的问题是当用户在第 1 部分向下滚动时,我如何触发滚动事件以滚动到第 2 部分,类似于特斯拉登录页面。

我已经使用 offsetY 上的侦听器和一个条件来实现它,如果它等于 100px if (offsetY === 100),则窗口将滚动到第 2 部分。但这只能在等效于 100 的情况下实现。换句话说,当且仅如果它相对于文档满足 100px。

任何想法或建议都会很有用。


function App() {
  const [offsetY, setOffSetY] = useState(0);

  const handleScroll = (e) => {
    setOffSetY(window.pageYOffset)
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [])

  useEffect(() => { // fires when the user scroll up or down, i.e. when the offsetY changes
    if (offsetY === 100) { // scroll to section 2 when the offsety is equal to 100px
      scroller.scrollTo("section2", {
        delay: 100,
        duration: 200,
        smooth: true
      })
    }
  }, [offsetY]);

  return (
    <React.Fragment>
        <div id="section1" style={{height:"500px", width:"100%", color:"black"}}>
        </div>
        <div id="section2" style={{height:"500px", width:"100%", color:"red"}}>
        </div>
    </React.Fragment>
  );
}

export default App;

4

0 回答 0