小编典典

React:尝试将onClick添加到li标记中,但单击处理程序函数未定义

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>);
  }
});

我想知道是否是因为我的范围设定错误?


阅读 250

收藏
2020-07-22

共1个答案

小编典典

设置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);
  ^^^^^

Example

2020-07-22