You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

滚动时无法为Header组件添加class的技术问题求助

问题修复方案

你的代码存在三个关键问题,导致滚动时无法正常添加/移除类名:

1. 未将Ref绑定到实际DOM元素

你定义了headerRef但没有在JSX中把它绑定到Header元素上,导致headerRef.current始终为null,自然无法操作类名。

2. 事件监听器无法正确卸载

移除监听器时没有传入对应的回调函数,window.removeEventListener("scroll")这种写法无效,监听器会一直留在内存中,还可能引发后续异常。

3. 回调函数引用丢失

直接在addEventListener里写匿名函数,后续无法获取同一引用进行移除操作。


修复后的完整代码

import React, { useRef, useEffect } from 'react'
import './header.css'

const Header = () => {
  const headerRef = useRef(null);

  // 抽离滚动回调函数,保留引用
  const handleScroll = () => {
    // 用window.scrollY更简洁,兼容多数场景
    if (window.scrollY > 80) {
      headerRef.current?.classList.add("header__shrink")
    } else {
      headerRef.current?.classList.remove("header__shrink")
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    // 移除时传入同一个回调函数引用
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [])

  // 必须把ref绑定到实际的header元素上
  return (
    <header ref={headerRef}>
      {/* 这里写入你的Header内容 */}
    </header>
  )
}

export default Header;

额外说明

  • headerRef.current?.classList是可选的空值保护,避免组件卸载后或ref未挂载时出现报错
  • window.scrollY等价于document.documentElement.scrollTop,写法更简洁
  • 确保你的header.css文件中存在header__shrink类的样式定义

内容的提问来源于stack exchange,提问作者Yun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:24:29