首页 > 解决方案 > 如何在 for 循环中声明 OnClick() 函数并每次传递不同的值?反应

问题描述

我正在尝试创建一个 React 组件列表。每个组件都包含一个按钮,该按钮需要有一个 onclick 事件。这个 onClick 事件需要传递一些随着外部循环的每次迭代而变化的变量。然而,这些变量的值对于每个组件并没有不同。我相信它们都传递了最终循环迭代的值。

我该如何解决这个问题?

我已经查看了使用闭包和 .map() 等的其他一些解决方案。但我似乎无法将它们正确应用于此。

performSearch = (query, searchIndex) => {

var resultsComponents = [];
var currentTeam = "";
var currentID = null;
var playerName = null;
var totalPoints = null;
let tempState = Object.assign({}, this.state)

//Iterate through the list of players
for (var i = 0; i < this.state.playerElementsData.length; i++) {
  //if the current players name contains the users search term
  if ((this.state.playerElementsData[i].first_name.toUpperCase() + " " + this.state.playerElementsData[i].second_name.toUpperCase()).includes(query.toUpperCase())) {

    //find the club the player belongs to
    for (var j = 0; j < this.state.teamsData.length; j++) {
      if (this.state.teamsData[j].id == this.state.playerElementsData[i].team) {
        currentTeam = this.state.teamsData[j].name
      }
    }

    //store the players details in variables. These need to be passed to the OnClick function
    currentID = this.state.playerElementsData[i].id
    playerName = this.state.playerElementsData[i].first_name + " " + this.state.playerElementsData[i].second_name
    totalPoints = this.state.playerElementsData[i].total_points

    //create a component containing this players details and add it to the list to be rendered
    resultsComponents.push(
      <div>
        <Card title={playerName} 
        extra={<Button type="primary" shape="circle" icon={<PlusOutlined />} onClick={() => this.selectPlayer(searchIndex, currentID, playerName, totalPoints, currentTeam)} />} >
          <p>{currentTeam} </p>
          <p>{" Points : " + totalPoints}</p>
        </Card>
      </div>
    );
  }
}

//render the list of components.
ReactDOM.render(resultsComponents, document.getElementById("results" + searchIndex));

};

标签: javascriptreactjsonclickantd

解决方案


推荐阅读