简体   繁体   中英

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. 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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM