Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...