使用 expo 提供的 expo-splash-screen
库可以很简单的处理启动页,文档地址 SplashScreen - Expo Documentation
安装
npx expo install expo-splash-screen
如果是裸 rn 项目,可以参考此处文档expo/packages/expo-splash-screen at sdk-50 · expo/expo (github.com)
使用
修改 App.tsx
import React, { useCallback, useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import Entypo from '@expo/vector-icons/Entypo';
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
// Keep the splash screen visible while we fetch resources
SplashScreen.preventAutoHideAsync();
export default function App() {
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
// 预加载字体
await Font.loadAsync(Entypo.font);
// 额外增加两秒的等待时间,这里可以处理自动登录或者其他异步操作,可以根据实际情况来调整
await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// 告诉程序可以渲染了
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// 这告诉启动画面立即隐藏!如果我们在调用 `setAppIsReady` 之后再调用这个,
// 那么在应用加载其初始状态并呈现其第一个像素时,我们可能会看到一个空白屏幕。
// 因此,我们在确保根视图已经执行布局后隐藏启动画面。
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
onLayout={onLayoutRootView}>
<Text>SplashScreen Demo! 👋</Text>
<Entypo name="rocket" size={30} />
</View>
);
}
修改启动页图片
打开 app.json
,修改 "expo.splash.image" 的路径即可
{
"expo": {
// ...
"splash": {
"image": "./assets/splash_2.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
}
}