我目前正在嘗試在表格的每一行上添加一個洗掉和編輯按鈕,我目前能夠讓這些按鈕運行這些功能就好了,但我遇到的一個大問題是我一生都無法弄清楚如何獲取該行的 ID 并將其變成一個變數,以便我插入該函式。`
function deletePet()
{
fetch("http://localhost:3001/api?act=delete&id=" pet.id "")
.then(res => res.json())
.then(
(result) => {
fetchPets();
})
}
function updatePet()
{
fetch("http://localhost:3001/api?act=update&id=2&animal=" name "&description=" desc "&age=" age "&price=" price "")
.then(res => res.json())
.then(
(result) => {
fetchPets();
});
}
return (<div>
<table>
<tbody>
<tr>
<th>Animal</th>
<th>Description</th>
<th>Age</th>
<th>Price</th>
<th>Action</th>
</tr>
{pets.map(pet => (
<tr key={pet.id}>
<td>{pet.animal}</td>
<td>{pet.description}</td>
<td>{pet.age}</td>
<td>{pet.price}</td>
<td><Button variant="contained" onClick={updatePet}>Edit</Button><Button variant="contained" onClick={deletePet}>Delete</Button></td>
</tr>
))}
所以基本上我想單擊 x 行上的洗掉按鈕,我希望使用洗掉寵物功能將其洗掉,正如您所看到的,我只是嘗試輸入 pet.id(這顯然不起作用哈哈哈)。任何幫助將不勝感激!
我試圖將鍵變成一個變數,將 pet.id 變成表中的一個變數,并在按鈕中創建一個嵌套函式,該函式只會洗掉該行,但也沒有用。
uj5u.com熱心網友回復:
function deletePet(pet) {
// do some with pet
}
function updatePet(pet) {
// do some with pet
}
... ... ...
<td><Button variant="contained" onClick={() => updatePet(pet)}>Edit</Button><Button variant="contained" onClick={() => deletePet(pet)}>Delete</Button></td>
你可以在點擊/按鈕pet
時傳遞物件來定義是編輯還是洗掉。edit
delete
uj5u.com熱心網友回復:
onClick={() => deletePet(pet.id)}
在洗掉按鈕和你的函式中嘗試:
function deletePet(id) {
fetch("http://localhost:3001/api?act=delete&id=" id "")
.then(res => res.json())
.then(
(result) => {
fetchPets();
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533605.html
標籤:反应