[英]how to implement a delete button , which deletes every specific row by clicking it?
它是一個程序,通過單擊“添加記錄”在每一行上簡單地獲取特定數據。 我很難執行刪除按鈕功能,單擊它時,該特定行將被刪除。 它應該在 DeleteHandler() 中實現。
import React, { useState } from 'react'
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${Math.floor(Math.random() * 10) + 1}`
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts,
json.name])
}
catch (error) {
console.log("error");
}
};
fetchData();
}
const DeleteHandler = (e) => {
const name = e.target.getAttribute("name")
console.log(name)
}
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) =>
<tr>
<td key={Math.random()}>{post}</td>
<td><button name={post} onClick={()=>DeleteHandler}>delete</button></td>
</tr>
)}
</table>
</div>
);
};
export default DataFetch
在您的 DeleteHandler() function 中,您應該能夠調用 setPosts() 並將帖子設置為自身減去被單擊的行,然后您的 JSX 將知道重新呈現自身並且該行應該不再存在。
使用此代碼
import React, { useState } from "react";
let uidArray = [];
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${
Math.floor(Math.random() * 10) + 1
}`;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts, json.name]);
} catch (error) {
console.log("error");
}
};
fetchData();
};
const DeleteHandler = (e) => {
const ele = document.getElementsByClassName(e)[0];
ele.remove();
};
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) => (
<tr className={post}>
<td key={Math.random()}>{post}</td>
<td>
<button name={post} onClick={() => DeleteHandler(post)}>
delete
</button>
</td>
</tr>
))}
</table>
</div>
);
};
export default DataFetch;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.