小编典典

在.map内部进行onClick反应,然后在另一个同级组件中更改数据

reactjs

使用React的第一天,我没有找到一种方法来让


阅读 279

收藏
2020-07-22

共1个答案

小编典典

bind(this)由于上下文内部发生.map变化,因此您必须使用匿名函数:

var audioListNodes = this.props.data.map(function(el, index) {
  return (
    <div author={el.voice}>
      {el.file}
      <button onClick={this.props.handleClickPlay}>Play</button>
    </div>
  );
}.bind(this));

另一个选择是开始使用按词法传递的ES6箭头函数this

var audioListNodes = this.props.data.map((el, index) => {
  return (
    <div author={el.voice}>
      {el.file}
      <button onClick={this.props.handleClickPlay}>Play</button>
    </div>
  );
});

正如@Henrik Andersson在评论中提到的那样,您也可以this直接传递给map

var audioListNodes = this.props.data.map(function(el, index) {
  return (
    <div author={el.voice}>
      {el.file}
      <button onClick={this.props.handleClickPlay}>Play</button>
    </div>
  );
}, this);
2020-07-22