当用户向上或向下滚动 react.js 时触发滚动事件

时间:2021-06-06 11:33:49

标签: javascript reactjs scroll react-hooks react-scroll

我正在尝试使用 React.js 和 Tesla

模拟 react-scroll 的网络应用登陆页面滚动行为

Scroll Behavior

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

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

我已经在 offsetY 上使用侦听器实现了它,如果它等于 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; ,则窗口将滚动到第 2 部分。但这只能在等于 100 时实现。换句话说,当且仅当它相对于文档达到 100px 时,窗口才会滚动。

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

https://codepen.io/donovanh/pen/rmzNZJ

0 个答案:

没有答案
相关问题