React: trying to add an onClick to a li tag but the click handler function is undefined

前端 未结 2 1706
温柔的废话
温柔的废话 2020-12-19 12:33

I am new to react, so I don\'t know much about it. I am trying to add a click handler to a li but the function seems to be undefined?

var ActivityList = Reac         


        
相关标签:
2条回答
  • 2020-12-19 13:07

    You can also use an arrow function to avoid binding this in the function at all:

    this.props.data.map(game =>
        <li onClick={this.handleClick} name={game.name}>{game.name}</li>
    )
    
    0 讨论(0)
  • 2020-12-19 13:19

    Set this to .map, because in .map callback this refers to global scope(in browser it is window or undefined if you use strict mode)

    this.props.data.map(function(game) {
      return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
    }, this);
      ^^^^^
    

    Example

    0 讨论(0)
提交回复
热议问题