For some reasons, I have to add an event listener for an html element inside useEffect
hook. And the element is from a component named 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. So the only way is to query ele
and then add event listener in useEffect
.
But this code didn't work. When using window.getEventListener(ele)
in devtools, it returned a null object without click
property. Also, the click
event didn't work. And I found the code below can work:
const App => {
const divRef = useRef(null)
useEffect(() => {
const handleClick = () => {}
const ele = divRef.curre开发者_JAVA百科nt.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.
精彩评论