我正在使用對打字稿做出反應。我從后端 API 獲取一些資料,然后使用該map函式呈現資料。地圖功能是回傳一張卡片,其中我有兩個按鈕,我想根據 key我在地圖功能上提供的內容執行一些操作。
作為兩個按鈕之一,有一個洗掉按鈕,它將id卡片發送到服務器進行洗掉。
{items &&
items.map((data) => {
if (option[index]) {
return <Grid item lg={3} md={4} sm={6} xs={11} key={data.Id}>
<Card className="home-card">
<CardMedia
component="img"
height="256px"
image={homeimg}
alt="green iguana"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{data.name}
</Typography>
</CardContent>
<CardActions>
<Button size="small" variant="contained">
More Details
</Button>
<Button
size="small"
variant="contained"
// Here I want to get the key that I provided to the Grid element
onClick={handleClickOpen}
>
Delete
</Button>
</CardActions>
</Card>
</Grid>
}
})}
獲得該密鑰的最佳方法是什么?
uj5u.com熱心網友回復:
因為 map 函式有效地回傳了當前迭代的所有資料,所以items您可以隨時在該函式中簡單地訪問您傳遞給鍵的值。假設您要處理其中的鍵值,handleClickOpen您可以將該值作為方法引數傳遞。
您還可能希望將一個函式傳遞給 onClick ,否則您將handleClickOpen在組件渲染后立即運行,而不是在用戶單擊按鈕時運行。
最后,這只是一種風格選擇,但您也可以解構專案中資料的值
{items &&
items.map({Id, name} => {
if (option[index]) {
return <Grid item lg={3} md={4} sm={6} xs={11} key={Id}>
<Card className="home-card">
<CardMedia
component="img"
height="256px"
image={homeimg}
alt="green iguana"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{name}
</Typography>
</CardContent>
<CardActions>
<Button size="small" variant="contained">
More Details
</Button>
<Button
size="small"
variant="contained"
onClick={() => (handleClickOpen(Id))}
>
Delete
</Button>
</CardActions>
</Card>
</Grid>
}
})}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482158.html
