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

React Native添加Google Font报错求助:求错误原因与解决方法

错误原因及解决办法

1. AppLoading 导入错误

你直接从expo导入AppLoading的写法是错误的——当前Expo的AppLoading组件已从主包中移出,需要单独安装并导入对应包。

2. 潜在的字体加载调试缺失

你的字体加载逻辑框架正确,但缺少错误捕获机制,无法排查字体路径错误或加载失败的问题。


具体修复步骤:

步骤1:安装expo-app-loading依赖

在项目根目录执行命令:

npx expo install expo-app-loading

步骤2:修正AppLoading导入语句

将原代码中的:

import AppLoading from 'expo';

替换为:

import AppLoading from 'expo-app-loading';

步骤3:添加错误捕获逻辑(推荐)

给AppLoading组件增加onError属性,方便调试字体加载失败的问题:

<AppLoading
  startAsync={getFonts}
  onFinish={() => setFontsLoaded(true)}
  onError={(err) => console.log('字体加载失败:', err)}
/>

步骤4:验证字体文件路径

确认./assets/Fonts/Raleway-VariableFont_wght.ttf路径准确,文件名大小写与实际文件一致(部分系统区分大小写)。

修复后的完整App.js代码:

import React, { useState } from 'react';
import Home from './Screens/Home';
import * as Font from 'expo-font'; 
import AppLoading from 'expo-app-loading';

const getFonts = () => Font.loadAsync({
  'rale': require('./assets/Fonts/Raleway-VariableFont_wght.ttf'),
}); 

export default function App() {
  const [fontsLoaded, setFontsLoaded] = useState(false);

  if (fontsLoaded) {
    return (<Home />);
  } else {
    return (
      <AppLoading
        startAsync={getFonts}
        onFinish={() => setFontsLoaded(true)}
        onError={(error) => console.error(error)}
      />
    );
  }
}

额外说明

若使用较新版本的Expo,也可选择expo-splash-screen替代AppLoading,这是官方推荐的更灵活的启动屏解决方案,但对于简单字体加载场景,上述修复方案已足够满足需求。

内容的提问来源于stack exchange,提问作者Lakindu Widuranga Alvis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:52:35