【问题标题】:Cannot read property [function] of undefined无法读取未定义的属性 [函数]
【发布时间】:2016-10-31 11:43:03
【问题描述】:

我的渲染函数的返回部分中有这个:

<table>
        <tbody>
          {nums.map(function(num, index){
            return <tr key={ index }>{num} <input type="submit" value="unmatch" onClick={this.unMatchButtonClicked} />
            </tr>;
          })}
        </tbody>
      </table>

但是当我加载页面时,我收到一条错误消息:Cannot read property 'unMatchButtonClicked' of undefined

虽然是render:function()之前的函数

unMatchButtonClicked: function(){
  console.log('called');
},

那么this 的范围是什么,为什么它是未定义的?

【问题讨论】:

  • 设置 this.map 回调 - nums.map(function(num, index){ /* code */ }, this)
  • @AlexanderT。干杯兄弟
  • @AlexanderT。不过,我对此有一个问题。它现在正在更改代码其他部分中的this,并将其他地方的变量设置为== 鼠标单击而不是this,它应该在其他地方。如果需要可以详细说明

标签: javascript reactjs this undefined


【解决方案1】:
  1. 选项:Array.map(function () {/*...*/}, this)
  2. 选项:var unMatchButtonClicked = this.unMatchButtonClickedonClick={unMatchButtonClicked}

除此之外,您应该考虑为您的点击处理程序使用箭头函数或将this 绑定到您的函数。
http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2018-04-01
    • 2020-03-26
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多