简体   繁体   English

React - 我怎样才能触发一个事件监听器一次?

[英]React - How can I fire an Event listener just once?

Let's say I have a button that only fires just once then the listener is removed.假设我有一个按钮,它只触发一次,然后侦听器被删除。 I've done this with vanilla Javascript我用香草 Javascript 完成了这个

const element = document.querySelector('#MyElement');
element.addEventListener('click', handleClick, {once: true});

I don't know how can I access this property with React synthetic events since this is putted directly in the component我不知道如何使用 React 合成事件访问此属性,因为它直接放在组件中

<button id="MyElement" onClick={handleClick}>Click me!</button>

Thanks谢谢

You can use useRef to do the same.你可以使用useRef来做同样的事情。 Demo link is here演示链接在这里

import React, { useEffect, useRef } from "react";

export default function App() {
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      ref.current.addEventListener("click", () => console.log('Clicked only once'), { once: true });
    }
  }, []);

  return (
    <div>
      <button ref={ref}>Click on me (Once)</button>
    </div>
  );
}

You can use a variable in state, probably a boolean for this您可以使用 state 中的变量,可能是 boolean

function App {
  const [buttonClicked, setButtonClicked] = useState(false);

  const handleClick = () => {
    setButtonClicked(true);
    // continue with the function 
  }

  return <button onClick = {
    buttonClicked ? () => {} : handleClick
  } > Click < /button>

}

Or you could just return from the handleClick或者你可以从 handleClick 返回

function App {
  const [buttonClicked, setButtonClicked] = useState(false);

  const handleClick = () => {
    if(buttonClicked){
      return; //simply return
    }
    setButtonClicked(true);
    // continue with the function 
  }

  return <button onClick={handleClick}> Click </button>

}

I would prefer the second option.我更喜欢第二种选择。

Flip the state once the element has triggered its event:一旦元素触发了它的事件,翻转 state:

handleClick() {
    this.setState({
        hasTriggered: true
    })
}

render() {
    return (
        <div>
            {
                !this.state.hasTriggered ?
                <MyElement onClick={this.handleClick.bind(this)} /> : null
            }
        </div>
    )
}
const [avoidExtraCall, setAvoidExtraCall] = useState(false);

const handleClick = () => {
  if(!avoidExtraCall){
    //Do what you want here then
    setAvoidExtraCall(true);
    //This if statement will only be executed once
  }
}

return (
  <button id="MyElement" onClick={handleClick}>
    Click me!
  </button>
);

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

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