You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为React JS网站添加启动页(Splash Screen)

React 实现启动页(Splash Screen)的通用方案

下面是两种React中实现启动页的通用代码,你可以根据需求定制样式、时长和内容:

方式一:基础定时器控制实现

适合简单场景,直接通过状态和定时器控制启动页的显示与隐藏:

import { useState, useEffect } from 'react';

function App() {
  const [showSplash, setShowSplash] = useState(true);

  useEffect(() => {
    // 设置启动页显示时长,这里设为6秒,可自行调整5-10秒区间
    const timer = setTimeout(() => {
      setShowSplash(false);
    }, 6000);

    // 组件卸载时清除定时器,避免内存泄漏
    return () => clearTimeout(timer);
  }, []);

  if (showSplash) {
    return (
      <div className="splash-screen">
        {/* 这里替换成你的启动页内容,比如logo、品牌名称等 */}
        <h1>你的品牌Logo</h1>
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <div className="app-content">
      {/* 你的首页内容 */}
      <h1>首页内容</h1>
    </div>
  );
}

export default App;

对应的基础CSS(可放入全局样式或组件样式文件):

.splash-screen {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffffff; /* 可替换为你的品牌背景色 */
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
}

方式二:结合CSS过渡动画的实现

添加淡出过渡效果,更贴近原生应用的启动体验:

import { useState, useEffect } from 'react';
import './SplashScreen.css';

function App() {
  const [showSplash, setShowSplash] = useState(true);
  const [fadeOut, setFadeOut] = useState(false);

  useEffect(() => {
    const showDuration = 7000; // 启动页显示时长
    const fadeDuration = 1000; // 淡出动画时长

    const timer = setTimeout(() => {
      setFadeOut(true);
      // 淡出完成后隐藏启动页
      setTimeout(() => setShowSplash(false), fadeDuration);
    }, showDuration);

    return () => {
      clearTimeout(timer);
    };
  }, []);

  if (!showSplash) {
    return (
      <div className="app-content">
        {/* 你的首页内容 */}
        <h1>首页内容</h1>
      </div>
    );
  }

  return (
    <div className={`splash-screen ${fadeOut ? 'fade-out' : ''}`}>
      {/* 定制你的启动页内容 */}
      <img src="/your-logo.png" alt="品牌Logo" />
      <p>正在初始化...</p>
    </div>
  );
}

export default App;

对应的CSS(SplashScreen.css):

.splash-screen {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #2196f3;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  transition: opacity 1s ease-out;
  opacity: 1;
}

.splash-screen.fade-out {
  opacity: 0;
  pointer-events: none; /* 动画过程中禁止点击 */
}

.splash-screen img {
  width: 150px;
  height: 150px;
  margin-bottom: 20px;
}

定制提示

  • 调整定时器的毫秒值(6000即6秒)来设置启动页显示时长
  • 修改.splash-screen的样式(背景色、布局、内容)匹配你的品牌
  • 可以在启动页中添加加载动画、进度条等元素
  • 如果需要等待API数据加载完成再隐藏启动页,可将定时器替换为数据加载完成后的回调逻辑

内容的提问来源于stack exchange,提问作者Sarimm Chaudhry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:15:33