[英]React. Add/Remove event listener
There are 6 posts with information about users.有 6 个帖子包含有关用户的信息。 If the name and email in the post are too big, they are cut off.如果帖子中的名称和email太大,则被截掉。 When hovering over the cropped element - a block with full information appears next to it.将鼠标悬停在裁剪的元素上时 - 旁边会出现一个包含完整信息的块。 If registration is successful - user list is updated - newest one in the beginning.如果注册成功 - 用户列表被更新 - 最新的在开始。 I put events onMouseOver and onMouseOut on items.我将事件 onMouseOver 和 onMouseOut 放在项目上。 Is it necessary to removeEventListener?是否需要移除EventListener? Tried to do it in return UseEffect, but selected items = null [There are current elements ][1]尝试这样做作为回报 UseEffect,但选定的项目 = null [有当前元素][1]
Read the article about events - https://en.reactjs.org/docs/handling-events.html阅读有关事件的文章 - https://en.reactjs.org/docs/handling-events.html
You can add events using useEffect
.您可以使用useEffect
添加事件。 return
triggered when component unmount .组件卸载时触发return
。 Code example:代码示例:
useEffect(() => {
function handleClick() {
console.log("click")
}
window.addEventListener("click", handleClick);
return () => window.removeEventListener("click", handleClick);
}, []);
You speak about onMouseOver, listener starting by "on" and which are put on tags, doesn't need a removeEventListener.你谈到onMouseOver,监听器以“on”开头并且放在标签上,不需要removeEventListener。 It's only when you used addEventListener.仅当您使用 addEventListener 时。 In react, addEventListener isn't used with some exceptions在反应中,addEventListener 不使用,有一些例外
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.