ReactJS can't access “this” methods

后端 未结 3 1807
余生分开走
余生分开走 2020-12-21 15:28

I am trying to pass a method to a child component to handle onclick events. I saw a lot of examples online, but I can\'t get it working. When I am inside the render function

3条回答
  •  -上瘾入骨i
    2020-12-21 15:59

    this is undefined because the map callback does not know what it is. The simplest way to solve this is to pass a second argument, and it will use that as this in the callback:

    var thumbsNodes = this.state.data.map(function(thumb) {
      console.log(this.handleClick)
      return 
    }, this)
    

    More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

提交回复
热议问题