ReactJS can't access “this” methods

后端 未结 3 1816
余生分开走
余生分开走 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条回答
  •  情书的邮戳
    2020-12-21 15:45

    If you're using a compiler like Babel as part of your development workflow, I'd suggest using arrow functions:

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

    As you can see, it's a nice compact syntax. The arrow function will preserve the this context for you. The Babel compiler produces JavaScript that uses a closure:

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

提交回复
热议问题