`this`没有作用于React Component事件处理程序

时间:2015-09-02 16:00:00

标签: javascript reactjs

我正在尝试新的React v0.13 ES6组件类,但我遇到了问题。当我尝试在类中使用单击处理程序时,调用组件通过props收到的函数会抛出一个错误,指出this未定义。

import React, { Component } from 'react';

class MyComp extends Component {
  render() {
    return (
      <div>
        <input type='button' value='Fetch Data' onClick={this.handleClick} />
      </div>
    );
  }

  handleClick(evt) {
    // ...do stuff

    this.props.fetch(); // throws error: `cannot read property 'this' of undefined`
  }
}

我仔细检查过,我可以从render函数中访问道具,所以我知道它们存在于它们应该的位置。

当我使用旧的React.createClass语法时,相同的代码工作正常,所以我想知道我是否错过了什么。我知道我可以通过在渲染函数中将this绑定到handleClick方法来轻松解决这个问题,但如果事情变得简单,我就不会这样做。

1 个答案:

答案 0 :(得分:1)

更改以下行:

<input type='button' value='Fetch Data' onClick={this.handleClick} />

进入这个:

<input type='button' value='Fetch Data' onClick={this.handleClick.bind(this)} />

或添加constructor以下内容:

constructor() {
  super();
  this.handleClick = this.handleClick.bind(this);
}

或者如果你使用的是ES7功能,你可以考虑创建自己的或using an existing autobind装饰器。

在某种程度上相关的说明:请考虑使用button元素。