javascript - 如何在 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));
};
解决方案
推荐阅读
- asp.net-mvc - GRID 中的列客户端模板
- c++ - 如何使用迭代器作为参数方法?
- android - Kivy Android 应用程序上的 Paramiko/SSH,可能吗?
- angular - 如何在 ngx-leaflet Angular 应用程序中加载和显示外部多多边形 geoJSON 文件
- php - 连接两个字符串并将其传递给 laravel 中的数组
- java - 使用规则使用户名唯一
- intellij-idea - Intellij/IDEA 切换器键映射
- html - Html/CSS 大小的图像
- php - For 循环正在通过电子邮件发送表格中的每行一个字符
- python-3.x - python字典中的语法