You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用Switch Navigator时如何在Expo中导入Google字体

不需要在每个页面单独导入字体,也不需要更换Switch Navigator的结构,两种常用方案可兼容你现有的配置:

方案1:调整App.js结构兼容官方字体加载指南

你只需要把原有的导航容器定义单独抽为变量,在默认导出的App组件中完成字体加载后再渲染导航即可,完全不影响原有Switch Navigator的配置逻辑:

import { useFonts } from 'expo-font';
import SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';

// 原有Switch Navigator配置抽为单独变量
const AppNavigator = createAppContainer(
  createSwitchNavigator(
    {
      Loading: LoadingScreen,
      App: AppStack,
      Auth: AuthStack,
    },
    {
      initialRouteName: "Loading"
    }
  )
)

export default function App() {
  // 加载自定义字体
  const [fontsLoaded] = useFonts({
    '你的自定义字体名': require('./assets/fonts/字体文件.ttf'),
    // 所有需要用到的字体都在此处配置
  });

  // 字体加载完成后再关闭启动屏,避免字体闪烁
  useEffect(() => {
    if (fontsLoaded) {
      SplashScreen.hideAsync();
    }
  }, [fontsLoaded]);

  if (!fontsLoaded) {
    return null;
  }

  // 字体加载完成后渲染导航
  return <AppNavigator />;
}

注意需要提前安装expo-font和expo-splash-screen依赖,并在app.json中配置启动屏autoHide为false。

方案2:复用现有Loading页面加载字体(无需修改App.js导出结构)

由于你的Switch Navigator初始路由就是Loading页面,你可以直接把字体加载逻辑放到LoadingScreen中,和原有加载逻辑合并,完全不用修改App.js的导出配置:

import * as Font from 'expo-font';
import { useEffect } from 'react';
import { View, ActivityIndicator } from 'react-native';

export default function LoadingScreen({ navigation }) {
  useEffect(() => {
    const initApp = async () => {
      // 加载自定义字体
      await Font.loadAsync({
        '你的自定义字体名': require('../assets/fonts/字体文件.ttf'),
        // 所有需要用到的字体都在此处配置
      });
      // 原有逻辑:判断登录状态、初始化资源等
      const isUserLogin = await checkLoginStatus();
      // 加载完成后跳转对应页面
      navigation.replace(isUserLogin ? 'App' : 'Auth');
    }
    initApp();
  }, [navigation]);

  return <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    <ActivityIndicator size="large" />
  </View>
}

两种方案加载的字体均为全局生效,所有页面直接通过fontFamily: '你的自定义字体名'引用即可。

内容的提问来源于stack exchange,提问作者kyriazo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:57:00