【问题标题】:react class method is not defined no-undef反应类方法未定义 no-undef
【发布时间】:2018-02-21 09:20:02
【问题描述】:

我是反应新手。我的应用程序运行正常,但添加 eslint(airbnb) 后,我的应用程序无法编译。

export default class HelloWorldComponent extends React.Component {
  render() {
    return (
      <div>
        <div>{this.props.message}</div>
        <button onClick={this.props.helloWorldClick}>Hello 
        World</button>
      </div>
    )
  }
  helloWorldClick = () => {
    console.log('here') 
  }
}

在 .eslintrc 文件上添加 { "parser": "babel-eslint" } 之前,它抛出了 eslint 错误

"[eslint] 解析错误:Unexpected token =" --在 helloWorldClick 箭头函数行。

添加解析器后,我没有任何 elsint 错误。但是运行应用程序时出现编译错误。

编译失败 ./src/component/HelloWorldComponent.js 第 18 行:'helloWorldClick' 未定义 no-undef

请告诉我如何解决此错误。

【问题讨论】:

    标签: reactjs react-redux eslint eslint-config-airbnb


    【解决方案1】:

    这里造成问题的不是箭头函数。类属性不是 ES6 规范的一部分。

    如果您希望能够转换此代码,则需要添加 class properties babel plugin

    或者,此转换作为 Babel 的 stage 2 preset 的一部分提供。

    使用带有类属性的箭头函数可确保始终以组件作为 this 的值调用方法,这意味着此处手动重新绑定是多余的。

    this.helloWorldClick = this.helloWorldClick.bind (this);
    

    【讨论】:

      【解决方案2】:

      我也遇到了这个问题。您可以将以下内容添加到每个组件文件的顶部,以防止出现“un-def”键错误消息,并且在不更改 es-lint 设置的情况下仍然使用箭头功能。

      /* eslint no-undef: 0 */ // --> OFF
      

      【讨论】:

        【解决方案3】:

        感谢您的回答。但我的问题不同。最后我解决了这个问题。通过将 eslint 版本降级到 3.19.0。它现在完美运行。

        【讨论】:

          猜你喜欢
          • 2018-05-16
          • 2019-07-23
          • 2019-07-29
          • 1970-01-01
          • 2021-10-16
          • 2018-06-09
          • 2018-10-02
          • 2021-05-26
          • 2021-06-17
          相关资源
          最近更新 更多