ReactJS can't access “this” methods

后端 未结 3 1806
余生分开走
余生分开走 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 <Thumb thumb={thumb} key={thumb.url} 
                    onClick={this.handlefunc.bind(this,thumb.url)}/>;
    });
    

    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 <Thumb thumb={thumb} key={thumb.url} 
                    onClick={_this.handlefunc.bind(_this,thumb.url)}/>;
    });
    
    0 讨论(0)
  • 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 <Thumb thumb={thumb} key={thumb.url} onClick={handlefunc.bind(this,thumb.url)}/>
    }, this)
    

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

    0 讨论(0)
  • 2020-12-21 15:59

    You need to grab a reference to this so it is the correct context when you call it.

    Try

    render: function() 
    {
      var handlefunc = this.handleClick; // i assume this is just for debugging the issue
      var self = this;
      var thumbsNodes = this.state.data.map(function(thumb) 
      {
         console.log(self.handleClick)  // note the use of `self`
      });
    }
    
    0 讨论(0)
提交回复
热议问题