简体   繁体   English

无法删除事件侦听器

[英]Cannot Remove Event Listener

Hello i tried to remove the event click event listener from a button.您好,我试图从按钮中删除事件单击事件侦听器。

In my real problem i have multiple scroolbars synced (whenever one changes the other scrolls to the same position) and i want to remove the onscroll event.在我的实际问题中,我同步了多个滚动条(每当一个将另一个滚动条更改为相同位置时)并且我想删除 onscroll 事件。

I oversimplified the example, but does not work.我过度简化了示例,但不起作用。 Any idea?任何的想法?

import { useRef } from "react";

var btnRef;

function clicked(){
    alert('btn clicked');
    if(btnRef.current){
        console.log('remove click listener ...')
        btnRef.current.removeEventListener('click', clicked);
    }
}

function MyComponent(){

    btnRef = useRef();

    return (
        <button ref={btnRef} onClick={clicked}>click me</button>
    );

}

export default MyComponent;
const [clicked, setClicked] = useState(false);

set clicked to true on button click, add logic to display based on boolean value在按钮点击时将 clicked 设置为 true,添加逻辑以根据 boolean 值显示

You need to use state and update it when the button is clicked for the first time, so whenever the button is clicked again, do nothing您需要使用 state 并在第一次单击按钮时更新它,因此每当再次单击按钮时,什么都不做

function MyComponent(){
  const [clicked, setClicked] = React.useState(false)

  function handleClick(){
      if(clicked){
        return undefiend
      }
      setClicked(true)
      alert('btn clicked');
  }

    return (
        <button disabled={clicked} onClick={handleClick}>click me</button>
    );

}
export default MyComponent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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