加载一个 gif 然后过渡到 reactjs 上的网页

Loading a gif then transition to the web page on reactjs

我在加载页面时有一个 React js 应用程序,开始时加载了一个 gif。我想要一种方法,使整个网站完全加载,然后 gif 将停止并进行转换以显示准备就绪的网站,此转换可以淡出或增加圆圈,目前 gif 是硬编码的,有超时吗如何做到这一点?

目前这是负责加载 gif 的代码:

loader.js 文件:

import loder from "../assets/gifs/loading.gif"
const Loader = () => {
    return (
        <div
        style={{
          background: "#F7D036",
          height:'100%',
          width:"100%"

        }}
      >
          
        <br/><br/><br/><br/><br/><br/><br/><br/><br/>  
        <center>
        <img src={loder} height="200" alt=""/></center>
         </div>
    )
}

app.js 文件:


  useEffect(() => {
  
    getAllCategories();
    setTimeout(() => setLoading(false), 2000);
  }, [getAllCategories]);

 return (
    <Router>
      {loading == true ? (
        <Loader />
      ) : (

some code ) 



我们可以使用 window.onload() 事件侦听器的方法,在你的情况下执行就像,你还需要使用状态来有效地管理它们

window.onload = (e) => {
    // your state changes here
    setLoading(false);
}

window.onload 侦听器将等待整个页面加载,您必须先启动加载程序,然后使用像

这样的 useEffect 切换此功能
useEffect(()=>{
    // 
    setLoading(true);
    // wrap the window.onload event inside a function and call it here
    windowLoadFunction();
}, [])

你好 max,根据评论, 所以我们可以做的是让你的加载器启动,就像你必须默认将加载器的状态设置为 true 一样,所以最初你的页面将开始加载, 因此,您可以使用 useState 属性 将其默认设置为 true,并向加载程序添加一个 css class 并添加一个 id,以便我们可以使用 [=24= 获取它](),因此如答案中所述,当我们将加载器状态切换为 false 时,我们可以通过像 document.getElementById("loader").className = "your animated css fade out class", 就是这样,所以,如果你想让你的加载器先淡出然后调用 class change 方法然后再你可以调用 setLoader class 为 false,

const [loading, setLoader] = useState(true);

useEffect(()=>{
  window.onload = ()=>{

     // changing class of the gif to fade out using css
     // change the time in this setTimeout function so that is it triggered as soon as your animation ends, match it with the animation duration, and have it started like 20 milli seconds before your animation ends,
     
     document.getElementById("loader").className = "fade-out-loader";
     setTimeout(()=>{
        //this will make sure the loader is not showed anymore, and your main content will popup 
        setLoader(false)
     }, 60) 
     
// match time of the loader out transition so the transition will be smooth
    
}
},[])

{!loading}?
  <div>Main content</div>:
  <div class = "loader-class" id = "loader">Loader element</div>

您的 css class 应该看起来像 (App.css)

.loader-class{
    dispaly:visible;
  }

.fade-out-loader{
   //add an fade animation to this class, you can get them at Animista
}