[英]How to add event listener for html element inside useEffect?
For some reasons, I have to add an event listener for an html element inside useEffect
hook.由于某些原因,我必须在
useEffect
挂钩中为 html 元素添加一个事件侦听器。 And the element is from a component named Comp
.该元素来自名为
Comp
的组件。 So I wrote this:所以我写了这个:
const Comp = () => {
return (
<div className="ele"></div>
// something else
)
}
const App = () => {
useEffect(() => {
const ele = document.querySelector(`.ele`)
const handleClick = () => {}
ele.addEventListener('click', handleClick)
return () => ele.removeEventListener('click', handleClick)
}, [])
return <Comp/>
}
I can't add event listener for ele
inside Comp
directly since Comp
is a third library component.我不能直接在
Comp
中为ele
添加事件监听器,因为Comp
是第三个库组件。 So the only way is to query ele
and then add event listener in useEffect
.所以唯一的办法就是查询
ele
然后在useEffect
中添加事件监听器。
But this code didn't work.但是这段代码不起作用。 When using
window.getEventListener(ele)
in devtools, it returned a null object without click
property.在 devtools 中使用
window.getEventListener(ele)
时,它返回了一个没有click
属性的 null object。 Also, the click
event didn't work.此外,
click
事件不起作用。 And I found the code below can work:我发现下面的代码可以工作:
const App => {
const divRef = useRef(null)
useEffect(() => {
const handleClick = () => {}
const ele = divRef.current.querySelector(`.ele`)
ele.addEventListener('click', handleClick)
return () => ele.removeEventListener('click', handleClick)
}, [])
return (
<div ref={divRef}> <Comp/></div>
)
}
So what is the corret way to solve this problem?那么解决这个问题的正确方法是什么? Why the first way failed while the second way succeeded?
为什么第一种方式失败而第二种方式成功了?
Using exactly the code you shared (the first snippet) it works perfectly fine, the listener is initiated.完全使用您共享的代码(第一个片段)它工作得很好,监听器被启动。 Instead of testing your code by using
window.getEventListener(ele)
just add some placeholder console.log
and try again.不要使用
window.getEventListener(ele)
来测试您的代码,只需添加一些占位符console.log
并重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.