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

如何解决ReactJS中使用screen.width时的no-restricted-globals报错?

解决React中使用screen.width时的ESLint报错问题

这个报错是因为你的项目里ESLint启用了no-restricted-globals规则,它把全局变量screen标记成了"受限",不允许直接使用。下面给你几个可行的解决办法:

  • 直接通过window对象访问(最推荐)
    全局的screen其实是window.screen的简写,直接调用window.screen.width就可以绕开ESLint的限制,而且逻辑上完全等价:

    // 这样就不会报错了
    console.log(window.screen.width);
    
  • 临时禁用该行的ESLint规则
    如果你不想修改全局配置,也可以在用到screen的代码行上方添加注释,临时关闭这条规则检查:

    // eslint-disable-next-line no-restricted-globals
    console.log(screen.width);
    
  • 修改ESLint配置,移除screen的限制
    打开项目的ESLint配置文件(比如.eslintrc.js、.eslintrc.json或者package.json里的eslintConfig字段),找到no-restricted-globals规则,把screen从受限列表中移除:

    {
      "rules": {
        "no-restricted-globals": ["error", "event", "fdescribe"]
        // 确保这里没有包含"screen"即可
      }
    }
    

这几种方法都能解决你遇到的报错问题,根据自己的项目需求选就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:23:10