简体   繁体   English

如何在反应组件上使用 setTimeout

[英]how to use setTimeout on a react component

This question might be simple to most web developers but I am pretty new and cannot figure out the way to put a settimeout function on what I would like to show on a page.对于大多数 Web 开发人员来说,这个问题可能很简单,但我还很陌生,无法弄清楚如何将 settimeout 函数放在我想在页面上显示的内容上。 below is the example of the code I would like to add a timeout for.下面是我想为其添加超时的代码示例。

import React from "react";

function Navbar() {
  return (
    <div className="navbar">
      <h4>
        <a href="#contact">Contact</a>
      </h4>
      <h4>About Me</h4>
    </div>
  );
}

export default Navbar;

and here is my app.jsx which then will be exported to be used in index.js .这是我的 app.jsx ,然后将其导出以在 index.js 中使用。 What I want is to have lets say 5s delay before my Navbar function shows.我想要的是在我的导航栏功能显示之前让我们说 5 秒延迟。

import React, { useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";

function App() {
  return (
    <div>
      <Navbar />
      <Contact />
    </div>
  );
}
export default App;

You can add setTimeout in your App Component.您可以在您的 App 组件中添加setTimeout It should look like this:它应该如下所示:

import React, { useState, useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";

function App() {
  const [showNavBar, setShowNavBar] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowNavBar(true);
    }, 5000);
    return () => clearTimeout(timer);
  }, [])

  return (
    <div>
      {showNavBar ? <Navbar /> : null}
      <Contact />
    </div>
  );
}
export default App;

your can add a state 'loading' and add useEffect hook and then use setTimeout there and change the loading state to false after 5seconds.您可以添加状态“正在加载”并添加 useEffect 钩子,然后在那里使用 setTimeout 并在 5 秒后将加载状态更改为 false。 in return section all you need to do is check if loading is false you show the otherwise it will show nothing.在返回部分,您需要做的就是检查加载是否为假,否则将不显示任何内容。

 import React, { useEffect, useState } from "react"; import Navbar from "./Navbar"; import Contact from "./Contact"; function App() { const [loading, setLoading] = useState(true); useEffect(() => { setTimeout(() => { setLoading(false); }, 5000); }, []) return ( <div> {!loading && <Navbar /> } <Contact /> </div> ); } export default App;

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

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