【问题标题】:`this` not scoped in React Component event handlers [duplicate]`this` 不在 React 组件事件处理程序的范围内 [重复]
【发布时间】:2015-11-28 05:46:21
【问题描述】:

我正在试用新的 React v0.13 ES6 组件类,但遇到了问题。当我尝试让类中的点击处理程序调用组件通过道具接收到的函数时,它会引发错误,指出未定义 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 方法轻松解决此问题,但如果它很简单,我宁愿不这样做。

【问题讨论】:

标签: javascript reactjs


【解决方案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 元素。

【讨论】:

  • constructor() { super(); this.handleClick = this.handleClick.bind(this); }
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 2017-06-14
  • 1970-01-01
  • 2012-12-14
  • 2015-06-26
  • 2015-06-17
相关资源
最近更新 更多