如何在React中正确检测滚动方向并实现元素跟随滚动位移
React滚动方向检测错误修复方案
核心错误原因
你代码中的逻辑顺序错误:在scrollPosition触发的副作用中,先将存储上一次滚动位置的prevScrollPosition.current赋值为了当前最新的滚动位置,再做大小对比,两个值完全相等,所以判断条件永远返回false。
修复后完整代码
import React, { useState, useEffect, useRef } from 'react'; import './App.css'; function App() { const [scrollPosition, setScrollPosition] = useState(window.scrollY); const prevScrollPosition = useRef(0); // 用ref存储DOM元素,避免重复查询 const scalpRef = useRef(null); const brainRef = useRef(null); useEffect(() => { const handleScroll = () => { setScrollPosition(window.scrollY); }; window.addEventListener('scroll', handleScroll); // 组件卸载时移除事件监听,避免内存泄漏 return () => window.removeEventListener('scroll', handleScroll); }, []) useEffect(() => { // 先对比上一次的滚动位置,判断方向 if (scrollPosition > prevScrollPosition.current) { // 向下滚动逻辑,先判断元素存在再操作 if (scalpRef.current) scalpRef.current.style.top = (scalpRef.current.offsetTop + 7) + "px"; if (brainRef.current) brainRef.current.style.top = (brainRef.current.offsetTop + 3) + "px"; } else { // 向上滚动逻辑 if (scalpRef.current) scalpRef.current.style.top = (scalpRef.current.offsetTop - 7) + "px"; if (brainRef.current) brainRef.current.style.top = (brainRef.current.offsetTop - 3) + "px"; } // 对比完成后,再更新上一次滚动位置为当前值,供下次判断使用 prevScrollPosition.current = scrollPosition; }, [scrollPosition]) return ( <div className="App"> <video className="cloudsVideo" autoplay playsinline loop muted src="Pexels Videos 3723.mp4" alt="clouds"></video> <video className="spaceVideo" autoplay playsinline loop muted src="pexels-ahnaf-piash-5747525.mp4" alt="space"></video> <img ref={scalpRef} className="scalp" src="scalp.png" alt="scalp"/> <img ref={brainRef} className="brain" src="Brain-PNG-Photos.png" alt="brain"/> <img className="head" src="head.png" alt="head"/> <h1>{scrollPosition}</h1> <h1>{prevScrollPosition.current}</h1> <h1>{scrollPosition - prevScrollPosition.current}</h1> </div> ); } export default App;
关键修改说明
- 调整了逻辑执行顺序:先拿上一次存储的滚动位置和当前滚动位置判断方向,执行对应元素移动逻辑后,再将当前滚动位置存入ref,作为下一次判断的基准值。
- 补充了滚动事件清理逻辑,组件卸载时自动移除监听,避免内存泄漏。
- 用useRef存储需要操作的DOM元素,避免每次触发逻辑都重复查询DOM,同时增加元素存在性判断,避免元素未挂载时操作报错。
- 移除了video标签重复的autoplay、muted属性,避免冗余。
内容的提问来源于stack exchange,提问作者Samuel Diaz
相关产品推荐
相关产品推荐

