React:尝试将onClick添加到li标签但单击处理程序功能未定义

use*_*283 3 reactjs

我是新手做出反应,所以我对此并不了解.我试图向li添加一个单击处理程序,但该函数似乎未定义?

var ActivityList = React.createClass({
  getInitialState: function() {
    return {name:"test"};
  },
  handleClick:function(e){
    console.log(e.target.name);
  },
  render:function(){
    return (
      <ul>
        {this.props.data.map(function(game){
         return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
        })
      }
      </ul>);
  }
});
Run Code Online (Sandbox Code Playgroud)

我想知道是不是因为我在这里找错了?

Ale*_* T. 13

设置this.map,因为在.map回调this中指的是全局范围(在浏览器中是window或者undefined如果您使用strict mode)

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

Example

  • 非常感谢,救命的:) (2认同)

Lyn*_*ynn 5

您还可以使用箭头功能来避免this在函数中绑定:

this.props.data.map(game =>
    <li onClick={this.handleClick} name={game.name}>{game.name}</li>
)
Run Code Online (Sandbox Code Playgroud)