React天气应用添加Lottie动画启动页的实现求助
实现React应用启动时的Lottie动画过渡效果
我是一名React.js初学者,跟着React天气应用教程做了一款带城市自动补全的天气应用,现在想实现用户访问时先显示Lottie动画,4秒后动画结束再展示应用内容,求帮忙实现。
我尝试写了VideoPlayer.jsx组件嵌入Lottie动画,用useEffect处理逻辑,代码如下:
const VideoPlayer = ({ onVideoEnd }) => { const [videoLoaded, setVideoLoaded] = useState(false); useEffect(() => { const handleVideoLoad = () => { setVideoLoaded(true); }; const handleVideoEnded = () => { if (onVideoEnd) { onVideoEnd(); } }; const videoElement = document.getElementById('myVideo'); videoElement.addEventListener('loadeddata', handleVideoLoad); videoElement.addEventListener('ended', handleVideoEnded); return () => { videoElement.removeEventListener('loadeddata', handleVideoLoad); videoElement.removeEventListener('ended', handleVideoEnded); }; }, [onVideoEnd]);
组件的返回部分和样式设置:
{!videoLoaded && <p>Loading video...</p>} <video id="myVideo" width="100%" height="100%" autoPlay muted> <source src="lottie.json" type="lottie/json" /> </video>
问题说明
video标签没法直接加载Lottie的JSON动画文件,得用专门的Lottie库来渲染。下面是正确的实现方案:
解决方案步骤
- 先安装Lottie React库
npm install lottie-react
- 新建SplashScreen组件(替换原来的VideoPlayer)
这个组件负责渲染Lottie动画,并处理结束回调:
import { useEffect, useState } from 'react'; import Lottie from 'lottie-react'; import splashAnimation from './lottie.json'; // 替换成你的动画文件路径 const SplashScreen = ({ onFinish }) => { const [isPlaying, setIsPlaying] = useState(true); useEffect(() => { // 两种结束逻辑二选一: // 选项1:动画自然播放完毕后切换到应用 const handleComplete = () => { setIsPlaying(false); onFinish(); }; // 选项2:强制4秒后结束,不管动画时长 // const timer = setTimeout(() => { // setIsPlaying(false); // onFinish(); // }, 4000); // return () => clearTimeout(timer); // 选项2需要加这个清理定时器的逻辑 return () => {}; }, [onFinish]); return ( <div style={{ position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', backgroundColor: '#ffffff', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}> <Lottie animationData={splashAnimation} autoplay={isPlaying} loop={false} onComplete={() => onFinish()} // 选项1的回调 style={{ width: '300px', height: '300px' }} // 调整动画大小 /> </div> ); }; export default SplashScreen;
- 在主App组件中使用SplashScreen
控制动画显示和应用内容的切换:
import { useState } from 'react'; import SplashScreen from './SplashScreen'; import WeatherApp from './WeatherApp'; // 你的天气应用组件 function App() { const [showSplash, setShowSplash] = useState(true); const handleSplashFinish = () => { setShowSplash(false); }; return ( <div className="App"> {showSplash ? ( <SplashScreen onFinish={handleSplashFinish} /> ) : ( <WeatherApp /> )} </div> ); } export default App;
关键说明
- Lottie动画是JSON格式的矢量动画,不是视频,必须用专用库渲染,video标签无法识别。
- 样式用fixed定位占满全屏,z-index确保动画在应用内容上方,避免被覆盖。
- 可以根据需求选择动画自然结束或强制4秒后结束的逻辑。
内容的提问来源于stack exchange,提问作者Sab Sidhu
相关产品推荐
相关产品推荐

