React 0.13 class method undefined

前端 未结 2 993
天涯浪人
天涯浪人 2021-01-12 09:49

So i\'ve started with React and ES6 and got stuck with very basics. Really appreciate some help.

handleClick() throws an error:

Uncaught TypeError: C         


        
相关标签:
2条回答
  • 2021-01-12 10:13

    react.js:18794 Warning: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See BlueBall

    so just like this:

    {
      menuItems.map(
         item => <li className={active ? 'active' : ''} 
      onClick={this.handleClick} key={item.id}>{item.text}</li>
    )}
    
    0 讨论(0)
  • 2021-01-12 10:36
    {menuItems.map(function(item) {
      return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>;
    })}
    

    Because your code is in strict mode (modules are always in strict mode), this is undefined inside the function you pass to .map.

    You either have to explicitly set the context by passing a second argument to .map:

    {menuItems.map(function(item) {
      // ...
    }, this)}
    

    Or use an arrow function:

    {menuItems.map(
         item => <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>
    )}
    
    0 讨论(0)
提交回复
热议问题