Expo CLI环境下如何将Lottie json动画用作React Native启动屏?
Expo项目集成Lottie动画作为启动屏实现方案
前置依赖补充
你已安装的lottie-react-native、lottie-ios@3.2.3可正常使用,额外需要安装expo-splash-screen用来控制原生启动屏的隐藏时机,避免出现白屏间隙:
npx expo install expo-splash-screen
将你准备好的Lottie动画JSON文件放入项目assets/animations/目录下,示例命名为splash-animation.json。
步骤1:修改app.json配置
在app.json的expo字段下添加expo-splash-screen插件配置,占位用的原生启动屏可以用纯色小图即可,仅作为过渡使用:
{ "expo": { // 保留原有的name、slug、sdkVersion等配置 "plugins": [ [ "expo-splash-screen", { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#ffffff" } ] ] } }
注意:backgroundColor需要和你的Lottie动画背景色保持一致,避免切换时出现明显色差
步骤2:根组件逻辑实现
以App.js为例,完整实现逻辑如下:
import { useEffect, useState, useRef } from 'react'; import { View, StyleSheet } from 'react-native'; import LottieView from 'lottie-react-native'; import * as SplashScreen from 'expo-splash-screen'; // 引入本地Lottie动画文件 import splashAnimation from './assets/animations/splash-animation.json'; // 阻止原生启动屏自动隐藏 SplashScreen.preventAutoHideAsync(); export default function App() { const [appInitDone, setAppInitDone] = useState(false); const lottieRef = useRef(null); useEffect(() => { const initApp = async () => { try { // 此处可添加APP启动前置逻辑:如资源预加载、用户登录态校验等 await Promise.all([ // 你的预加载任务列表 ]) } catch (err) { console.error('APP初始化失败', err); } finally { setAppInitDone(true); } } initApp(); }, []) // Lottie动画播放完成回调 const handleAnimationEnd = () => { // 隐藏原生启动屏 SplashScreen.hideAsync(); // 此处添加页面跳转逻辑:如跳转到首页、引导页、登录页 } if (!appInitDone) return null; return ( <View style={styles.container}> <LottieView ref={lottieRef} source={splashAnimation} autoPlay loop={false} onAnimationFinish={handleAnimationEnd} resizeMode="cover" style={styles.animation} /> {/* 此处添加你的APP根路由组件 */} </View> ) } const styles = StyleSheet.create({ container: { flex: 1 }, animation: { width: '100%', height: '100%' } })
常见问题处理
- iOS端生产构建动画不显示:确认
lottie-ios版本为3.2.3,无需额外修改原生配置 - 动画播放完成后白屏:检查原生启动屏的隐藏时机是否正确,确认根路由组件已正常挂载
- 低版本Expo SDK适配:SDK 46及以下版本需要额外执行
npx expo prebuild --clean生成原生配置后再构建
内容的提问来源于stack exchange,提问作者Alper Taş
相关产品推荐
相关产品推荐

