如何在滚动超过指定像素值时为元素添加类?我的代码为何失效?
问题分析与解决方案
你的代码无法生效的核心原因是:这段表达式只会在组件首次渲染时计算一次window.pageYOffset的值,后续页面滚动时,组件不会自动重新计算这个值,也就不会更新className。
另外还有个小问题:当条件不满足时你返回了null,这会导致最终的className变成arrowup null,多出一个无效的null类名,应该换成空字符串。
修复方案
使用React的状态结合滚动事件监听,实时更新滚动状态:
import { useState, useEffect } from 'react'; function YourComponent() { // 用状态跟踪是否达到滚动阈值 const [isScrollThresholdMet, setIsScrollThresholdMet] = useState(false); useEffect(() => { // 定义滚动处理函数 const handleScroll = () => { setIsScrollThresholdMet(window.pageYOffset >= 2); }; // 添加滚动事件监听 window.addEventListener('scroll', handleScroll); // 组件卸载时移除监听,避免内存泄漏 return () => window.removeEventListener('scroll', handleScroll); }, []); return ( <div className={`arrowup ${isScrollThresholdMet ? "showscroll" : ""}`}> {/* 你的元素内容 */} </div> ); }
内容的提问来源于stack exchange,提问作者Priscilla-Egberi
相关产品推荐
相关产品推荐

