首页指南参考教程

外观元素

了解如何在使用 Expo Router 的应用中使用启动画面、字体和图片。


你可以使用三个主要元素来自定义应用的外观:

  • 字体
  • 图片
  • 启动画面

字体

在 Expo Router v3 及更高版本中,你可以直接从 expo-splash-screen 导入 SplashScreen。

Expo Router 扩展了 expo-splash-screen API 以防止白闪。 将其与 expo-font 结合使用,以在加载字体时保持启动屏幕可见:

app/_layout.js
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 以获得最佳的跨平台体验:

Icon
Expo 图片 API 参考

有关如何安装和使用 expo-image 的更多信息,请参阅其 API 文档。

启动画面

原生平台需要启动画面。 Expo Router 会自动编排原生初始屏幕,使其保持可见,直到呈现第一个路由,这适用于用户深度链接到的任何路由。 要启用此功能,请在项目中安装 expo-splash-screen。

默认行为是在渲染第一个路由时隐藏启动屏幕,这对于大多数路由来说是最佳的。 对于某些路由,你可能希望延长启动屏幕,直到其他数据或资源加载结束。 这可以通过 expo-routerSplashScreen 模块来实现。 如果在隐藏启动屏幕之前调用 SplashScreen.preventAutoHideAsync,则启动屏幕将保持可见,直到调用 SplashScreen.hideAsync() 函数为止。

app/index.tsx
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 导航主题

React Navigation 导航器 <Stack><Drawer><Tabs> 使用共享外观提供程序。 在 React Navigation 中,你可以使用 <NavigationContainer /> 组件设置整个应用的主题。 Expo Router 管理根容器,以便你可以直接使用 ThemeProvider 设置主题。

app/_layout.tsx
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 导航元素

@react-navigation/elements 库提供了一组可用于构建导航 UI 的 UI 元素和辅助程序。 这些组件被设计为可组合和可定制的。 你可以重用库中的默认功能或在其之上构建导航器的 UI。

要将其与 Expo Router 一起使用,你需要安装该库:

Terminal
npm install @react-navigation/elements
Terminal
yarn add @react-navigation/elements

要了解有关该库提供的组件和实用程序的更多信息,请参阅 元素库 文档。

Expo 中文网 - 粤ICP备13048890号