[英]React + TS: How to pass a parameter from redirect function to onClick
[英]How to pass the key used from JSON response objects in a map as a parameter for onclick() function in React?
我嘗試從服務器創建一個“聯賽”對象列表,用戶可以單擊以成功創建聯賽,但要加入聯賽,用戶需要單擊圖標,並且需要將參數發送到 joinLeague () function 作為 League.leagueId 是 API 加入聯盟所必需的:
LeagueList 組件:
constructor(props) {
super(props);
this.state = {
leagues: []
};
this.createLeague = this.createLeague.bind(this);
this.joinLeague = this.joinLeague.bind(this);
}
joinLeague() {
const payload = {
"username": localStorage.getItem("username"),
"leagueId":
};
fetch(JOIN_LEAGUE_URL, {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": localStorage.getItem("token")
},
body: JSON.stringify(payload)
})
.then(response => response.json())
.then();
}
render() {
const {leagues} = this.state;
const leagueList = leagues.map(league => {
return <tr key={league.leagueId}>
<td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
<td>{league.playerCount}/10</td>
<td>{league.matchesPerPlayer}</td>
<td>{league.numberOfGamesPlayed}</td>
<td>{league.totalGamesToBePlayed}</td>
<i className="fas fa-plus" onClick={this.joinLeague}></i>
</tr>
});
}
在上面的 joinLeague() function 中,您可以看到我正在嘗試創建有效負載,但我需要來自 的 LeagueId 作為參數。
我怎樣才能做到這一點? 我試過 {this.joinLeague.bind(league)} 但沒有用,謝謝。
如果您使用箭頭 function,它應該將自身綁定到 scope(保持當前值league
)
你可以試試這樣的東西嗎?
render() { const {leagues} = this.state; const leagueList = leagues.map(league => { return <tr key={league.leagueId}> <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td> <td>{league.playerCount}/10</td> <td>{league.matchesPerPlayer}</td> <td>{league.numberOfGamesPlayed}</td> <td>{league.totalGamesToBePlayed}</td> <i className="fas fa-plus" onClick={() => this.joinLeague(league.leagueId)}></i> </tr> }); }
joinLeague(leagueId) { const payload = { "username": localStorage.getItem("username"), "leagueId": leagueId }; fetch(JOIN_LEAGUE_URL, {...
這是一個最小示例的鏈接,顯示現在可以在leagueId
中使用joinLeague
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.