简体   繁体   中英

React call component's method from nested function in render method

I would like to call the method updateCurrentThread onCLick, however I'm getting following error:

Uncaught TypeError: Cannot read property 'updateCurrentThread' of undefined

updateCurrentThread: function(thread) {
  this.setState({
  currentThread: thread
 }).bind(this);
},


render: function () {
  var threads = this.state.data.map(function (thread) {
    var boundClick = this.updateCurrentThread.bind(this, i);
    let time = getThreadDate(thread.timestamp);
    return (
      <div className="row thread" key={thread.threadID}>
        <ThreadParticipants onClick={boundClick} key={i} className="small-2 small-centered columns" ids={thread.participantIDs}/>
      </div>
  );
})

The this inside your function is scoped to the function, not the component. If you are able to use ES6 arrow functions, which are lexically scoped, then your current approach will work. Before arrow functions, people would store the component this in a variable (eg var self = this ) and then self.updateCurrentThread .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM