了解如何在使用 Expo Router 的应用中使用启动画面、字体和图片。
你可以使用三个主要元素来自定义应用的外观:
在 Expo Router v3 及更高版本中,你可以直接从
expo-splash-screen
导入 SplashScreen。
Expo Router 扩展了 expo-splash-screen
API 以防止白闪。 将其与 expo-font
结合使用,以在加载字体时保持启动屏幕可见:
import { Text, View } from 'react-native';
import {
SplashScreen,
// This example uses a basic Layout component, but you can use any Layout.
Slot,
} from 'expo-router';
import { useFonts, Inter_500Medium } from '@expo-google-fonts/inter';
SplashScreen.preventAutoHideAsync();
export default function Layout() {
const [fontsLoaded, fontError] = useFonts({
Inter_500Medium,
});
useEffect(() => {
if (fontsLoaded || fontError) {
// Hide the splash screen after the fonts have loaded (or an error was returned) and the UI is ready.
SplashScreen.hideAsync();
}
}, [fontsLoaded, fontError]);
// Prevent rendering until the font has loaded or an error was returned
if (!fontsLoaded && !fontError) {
return null;
}
// Render the children routes now that all the assets are loaded.
return <Slot />;
}
在 SDK 50 及以上版本中,Expo Router 的 静态渲染 提供了 自动静态优化 用于网页上的字体加载。 这实现了在浏览器中使用字体的最佳实践。
我们建议你使用 Expo Image 以获得最佳的跨平台体验:
有关如何安装和使用 expo-image 的更多信息,请参阅其 API 文档。
原生平台需要启动画面。 Expo Router 会自动编排原生初始屏幕,使其保持可见,直到呈现第一个路由,这适用于用户深度链接到的任何路由。 要启用此功能,请在项目中安装 expo-splash-screen。
默认行为是在渲染第一个路由时隐藏启动屏幕,这对于大多数路由来说是最佳的。 对于某些路由,你可能希望延长启动屏幕,直到其他数据或资源加载结束。 这可以通过 expo-router
的 SplashScreen
模块来实现。 如果在隐藏启动屏幕之前调用 SplashScreen.preventAutoHideAsync
,则启动屏幕将保持可见,直到调用 SplashScreen.hideAsync()
函数为止。
import { SplashScreen } from 'expo-router';
SplashScreen.preventAutoHideAsync();
export default function App() {
const [isReady, setReady] = React.useState(false);
React.useEffect(() => {
// Perform some sort of async data or asset fetching.
setTimeout(() => {
// When all loading is setup, unmount the splash screen component.
SplashScreen.hideAsync();
setReady(true);
}, 1000);
}, []);
return <Text>My App</Text>;
}
React Navigation 导航器 <Stack>
、<Drawer>
和 <Tabs>
使用共享外观提供程序。 在 React Navigation 中,你可以使用 <NavigationContainer />
组件设置整个应用的主题。 Expo Router 管理根容器,以便你可以直接使用 ThemeProvider
设置主题。
import { ThemeProvider, DarkTheme, DefaultTheme, useTheme } from '@react-navigation/native';
import { Slot } from 'expo-router';
export default function RootLayout() {
return (
<ThemeProvider value={DarkTheme}>
<Slot />
</ThemeProvider>
);
}
你可以在应用的任何层使用此技术来设置特定布局的主题。 可以使用 useTheme
从 @react-navigation/native
访问当前主题。
@react-navigation/elements
库提供了一组可用于构建导航 UI 的 UI 元素和辅助程序。 这些组件被设计为可组合和可定制的。 你可以重用库中的默认功能或在其之上构建导航器的 UI。
要将其与 Expo Router 一起使用,你需要安装该库:
-
npm install @react-navigation/elements
-
yarn add @react-navigation/elements
要了解有关该库提供的组件和实用程序的更多信息,请参阅 元素库 文档。