【问题标题】:Disable eslint error in jsx在 jsx 中禁用 eslint 错误
【发布时间】:2017-06-10 10:39:47
【问题描述】:

我的一个 react-native 组件中有以下 JSX

        <TouchableOpacity onPress={this.onEnableNotifications} style={{marginHorizontal: 10}}>
          <Image source={require('../../img/ic_warning.png')} style={{tintColor: colorThemes.Blue.red}}/>
        </TouchableOpacity>

我收到以下 ESLint 错误:

'require' is not defined. (no-undef)

我尝试在Image 之后添加行{ // eslint-disable-line no-undef },但这会导致解析错误。我怎样才能摆脱这个错误只是为了那条线。

【问题讨论】:

    标签: reactjs react-native react-jsx eslint


    【解决方案1】:

    在您的.eslintrc 文件中:

    {
        "globals":{
            "require": true
        }
    }
    

    【讨论】:

    • 嗨@Eldelsheel,感谢您的回答。我试图找到上面的行做了什么,但在 ESLint 文档中没有找到任何东西。上述行是否全局定义了require 函数?
    • 是的,像全局名称 ESLint 不会打扰你。其他示例:__DEV__$
    • 很好的提示,我可以使用它消除Promise__DEV__ 的相同错误。谢谢!
    【解决方案2】:

    我读到有一些 jsx quirks 所以试着把它分开:

    <TouchableOpacity onPress={this.onEnableNotifications} style={{marginHorizontal: 10}}>
      <Image
        source={require('../../img/ic_warning.png')} // eslint-disable-line no-undef
        style={{tintColor: colorThemes.Blue.red}}
      />
    </TouchableOpacity>
    

    或者你可以在上面定义。

    const warningImage = require('../../img/ic_warning.png'); // eslint-disable-line no-undef
    
    ....
    
    <TouchableOpacity onPress={this.onEnableNotifications} style={{marginHorizontal: 10}}>
      <Image source={warningImage} style={{tintColor: colorThemes.Blue.red}}/>
    </TouchableOpacity>
    

    如果这是一个静态路径,我将把它完全定义在反应类/函数之外,作为一个导入。

    【讨论】:

      【解决方案3】:

      为了在 jsx 中使用 cmets 禁用 eslint 警告

      { /* eslint-disable no-undef */ }
           <div>element causing warning </div>
      { /* eslint-enable no-undef */ }
      

      单行注释不起作用:

      { /* eslint-disable-line no-undef */ }
      

      另见

      https://github.com/eslint/eslint/issues/7030

      【讨论】:

        【解决方案4】:

        要禁用属性的 eslint 规则,可以使用内联注释:

        <StatusBar
          // eslint-disable-next-line react/style-prop-object
          style='light'
        />
        

        【讨论】:

          猜你喜欢
          • 2018-08-05
          • 2018-05-26
          • 2018-06-04
          • 1970-01-01
          • 2019-05-05
          • 2019-06-25
          • 2019-05-02
          • 2018-01-18
          • 1970-01-01
          相关资源
          最近更新 更多