英文:
e.target.value JavaScript not working accurate on onClick element when is clicked couple times
问题
I have a td element in React with an onClick event that sends the td's ID to a backend Node.js server for deletion from the database. Sometimes, e.target.id becomes empty, but the element has an ID. This issue occurs intermittently. The ID comes from another Axios.get and is mapped in React. I also attempted using promises, but the problem remains.
<td
className="deletebutton"
id={list.id}
onClick={async (e) => {
const deleteid = await e.target.id;
const socket = io(`http://${process.env.REACT_APP_RUN}:3001`, {
transports: ["websocket", "polling", "flashsocket"]
});
await axios.post(
`http://${process.env.REACT_APP_RUN}:3001/api/delete/single`,
{
idDelete: "" + deleteid + ""
}
);
await socket.emit("get date", ip);
}}
>
delete
<i>
<IconContext.Provider value={{ size: "16px", className: "factor-icons" }}>
<div>
<AiFillDelete />
</div>
</IconContext.Provider>
</i>
</td>;
英文:
I have td in react that has on click event function , the function sends id of td to the backend node.js
and the backend will delete that from database
here is my problem
sometimes e.target.id gets empty enter image description here but the element has id enter image description here
when I look in Chrome debugger,
why is this happing ?? but sometimes its works fine enter image description here
the id is from another Axios.get and mapped in react
<td
className="deletebutton"
id={list.id}
onClick={async (e) => {
const deleteid = await e.target.id;
const socket = io(`http://${process.env.REACT_APP_RUN}:3001`, {
transports: ["websocket", "polling", "flashsocket"]
});
await axios.post(
`http://${process.env.REACT_APP_RUN}:3001/api/delete/single`,
{
idDelete: "" + deleteid + ""
}
);
await socket.emit("get date", ip);
}}
>
delete
<i>
<IconContext.Provider value={{ size: "16px", className: "factor-icons" }}>
<div>
<AiFillDelete />
</div>
</IconContext.Provider>
</i>
</td>;
I tried promises but it has the same problem
答案1
得分: 0
你真的需要从e.target.id获取id吗?
这不是在Reactjs中建议的做法。
如果它们相同,可以直接使用列表中的list.id。
所以你的代码应该像这样:
...
id={list.id}
onClick={async (e) => {
const deleteid = list.id;
...
}}
...
英文:
Do you really need to get the id from the e.target.id?
That's not a recommended way of doing things in Reactjs.
The id could be used from the way you have it in the list.id if they are the same.
So you code should look like this instead
...
id={list.id}
onClick={async (e) => {
const deleteid = list.id;
...
}}
...
答案2
得分: 0
你好,感谢你@SimoneRossaini,
在这种情况下,使用 e.currentTarget.id 是有效的。
但是在这种情况下,e.target.id 和 e.currentTarget.id 有什么区别?
以及为什么有时候 e.target.id 有效,有时候不起作用?
英文:
hi thank you @SimoneRossaini
it is work with e.currentTarget.id in this case
but what is diffrence between e.target.id and e.currentTarget.id in this case
and how sometimes e.target.id works good and sometimes not
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论