如何实现删除按钮,该按钮通过单击它来删除每个特定行?
它是一个程序,只需单击“添加记录”,它只是在每个行上获取特定数据。我很难执行删除按钮功能,在单击它时,该特定行将被删除。它应在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
Its a program, which simply fetches a specific data, on every row by clicking "add record". I am having difficulty to execute delete button functionality , where on clicking it, that particular row will be deleted. Its should be implemented in 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此代码
https://codesandbox.io/s/smoosh-breeze-breeze-breeze-breeze-rreeze-breeze-rreeze-rreeze-rreeze-rreeze-rreeze-reas-rreeze-rreeze-rx7s0b
Use this code
https://codesandbox.io/s/smoosh-breeze-rx7s0b
在您的deletehandler()函数中,您应该只能调用setPosts()并将帖子设置为自身减去单击的行,然后您的JSX知道可以自行渲染,并且该行不再存在。
Within your DeleteHandler() function you should just be able to call setPosts() and set the posts to itself minus the row that was clicked, and then your JSX will know to re render itself and the row should no longer be there.