admin管理员组

文章数量:1389750

Let's say I have a button that only fires just once then the listener is removed. I've done this with vanilla 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 ponent

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

Thanks

Let's say I have a button that only fires just once then the listener is removed. I've done this with vanilla 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 ponent

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

Thanks

Share Improve this question asked Jan 8, 2021 at 7:37 ChimiChimi 331 silver badge4 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4

You can use useRef to do the same. 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>
  );
}

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>
);

You can use a variable in state, probably a boolean for this

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

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 :

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

render() {
    return (
        <div>
            {
                !this.state.hasTriggered ?
                <MyElement onClick={this.handleClick.bind(this)} /> : null
            }
        </div>
    )
}

本文标签: javascriptReactHow can I fire an Event listener just onceStack Overflow