简体   繁体   中英

Remove event listener added by click event, not in useEffect

I have an table rendered by an component.

On each td, i have function onClick

<table>
  <tbody>
    <tr>
      <td onClick={handleClick}>a</td>
      <td onClick={handleClick}>a</td>
      <td onClick={handleClick}>a</td>
    </tr>
  </tbody>
</table>

On handleClick function, i add 3 more event listener: movedown, mousemove, mouseup to track the mouse for selecting

handleClick = (event) => {
  const mousedown = (e) => {...}
  event.target.addEventListener("mousedown", mousedown)
  const mousemove = (e) => {...}
  const mouseup = (e) => {
    document.getElementById("tbl").removeEventListener("mousemove", mousemove);
  }
  document.getElementById("tbl").addEventListener("mousemove", mousemove);
  document.getElementById("tbl").addEventListener("mouseup", mouseup);
}

The problem is: i can not remove mouseup event after each click, so there are many duplicates of mouseup event like this:

复制

I try to use the similar as useEffect at the end of handleClick:

return () => document.getElementById("tbl").removeEventListener("mouseup", mouseup);

but it seems not working

Can you help me to solve this? Many thanks

Try to use onmouseout to remove your event. useEffect return func only run when your tbl unmount:D

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