React element'的方法在绑定到map()函数中时表现出奇怪的行为

React element's method shows weird behaviour when bound inside map() function

本文关键字:函数 element 方法 map 绑定 React      更新时间:2023-09-26

我在学习ReactJS的早期,遇到了一个非常令人困惑(和恼人!)的问题,当使用Array.prototype.map()方法渲染多个元素时。我在网上搜索了这个解决方案,也看了几本没有成功的书。下面是我要实现的代码:

var ExampleComponent = React.createClass({
  handleClick: function(event) {
    event.preventDefault();
    console.log("Click is working");
  },
  getInitialState: function() {
    return {
      exampleArray: ["one", "two", "three"]
    };
  },
  render: function() {
    return (
      <div>
        {this.state.exampleArray.map(function(item, index) {
          return (
            <button className={item} key={index} onClick={this.handleClick}>{item}</button>
          );
        })}
      </div>
    );   
  }
});

按钮渲染得很好。我希望在单击它们中的任何一个时,指定的字符串将登录到控制台中。相反,点击按钮会导致页面重新加载……感觉我在这里遗漏了一些关于React如何工作的明显的东西。

以前有人遇到过这个问题吗?罪魁祸首是什么?是否有更好的方法来实现相同的模式?

对这个问题的任何意见都将非常感谢!

您需要使用父上下文调用map():

// Call map with context.
{this.state.exampleArray.map(function(item, index) {
  return (
    <button className={item} key={index} onClick={this.handleClick}>
      {item}
    </button>
  );
}, this)}
// Call map with implicit context via arrow function.
{this.state.exampleArray.map((item, index) => {
  return (
    <button className={item} key={index} onClick={this.handleClick}>
      {item}
    </button>
  );
})}

参见组件间通信