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

React中遇"Unexpected use of 'scrollY' no-restricted-globals"错误求助

解决React中window.scrollY触发ESLint的no-restricted-globals错误

方法一:修改ESLint配置文件

1. 定位配置文件

ESLint配置文件一般在项目根目录,常见形式有:

  • .eslintrc.js(最常用)
  • .eslintrc.json
  • .eslintrc
  • 若用Create React App创建项目,配置可能在package.json的eslintConfig字段内

2. 调整规则

打开配置文件,在rules节点下添加或更新no-restricted-globals规则,允许scrollY使用:

示例(.eslintrc.js):

module.exports = {
  // 其他配置项...
  rules: {
    // 其他规则...
    "no-restricted-globals": [
      "error",
      {
        "name": "scrollY",
        "message": "请使用 window.scrollY 替代直接调用 scrollY"
      }
    ]
  }
};

如果你的配置中no-restricted-globals原本是数组形式(列出多个受限全局变量),只需确保scrollY不在列表里:

module.exports = {
  rules: {
    "no-restricted-globals": ["error", "event", "fdescribe"] // 移除scrollY
  }
};

方法二:在组件文件添加全局注释

在Navbar.jsx最顶部添加注释,告知ESLintscrollY是允许的全局变量:

/* global scrollY */

import { useEffect } from 'react';

const Navbar = () => {
  // ...组件代码
};

额外优化:修复滚动监听内存泄漏

你的当前代码会在组件每次渲染时新增滚动监听,导致重复触发和内存泄漏。建议用React的useEffect管理监听生命周期:

import { useEffect } from 'react';

const Navbar = () => {
  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 100) {
        console.log('hello');
      }
    };

    window.addEventListener('scroll', handleScroll);

    // 组件卸载时移除监听
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []); // 空依赖数组,仅在组件挂载/卸载时执行

  return (
    <nav className='w-full py-3 flex justify-between items-center fixed top-0 z-50 nav' >
      <div>Hello</div>
    </nav >
  );
};

export default Navbar;

内容的提问来源于stack exchange,提问作者Mohammad Yaseen Afridi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:36:29