Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How do I automatically trigger a button click after 5 seconds with React?

I have an 'Accept' button which I would like to be automatically clicked after 5 seconds. I'm using React with Next.js. The button code is:

<button name="accept" className="alertButtonPrimary" onClick={()=>acceptCall()}>Accept</button>

If I can't do this, I would like to understand why, so I can improve my React and Next.js skills.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm guessing you want this activated 5 seconds after render, in that case, put a setTimeout inside of the useEffect hook, like so. this will call whatever is in the hook after the render is complete. Although this isn't technically activating the button click event.

useEffect(() => {
  setTimeout(() => {
     acceptCall()
  }, timeout);
}, [])

in that case you should use a ref like so,

const App = () => {
  const ref = useRef(null);

  const myfunc = () => {
    console.log("I was activated 5 seconds later");
  };

  useEffect(() => {
    setTimeout(() => {
      ref.current.click();
    }, 5000); //miliseconds
  }, []);

  return (
    <button ref={ref} onClick={myfunc}>
      TEST
    </button>
  );
};

Hopefully, this is what you are looking for.

https://codesandbox.io/s/use-ref-forked-bl7i0?file=/src/index.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...