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

RN Expo应用自定义字体加载报错,请求排查问题原因

React Native 自定义字体加载失败排查与修复

问题详情

想要在RN应用中一次性导入自定义字体供所有组件使用,编写了如下代码:

fontConfig.js

import * as Font from 'expo-font';

const loadFonts = async () => {
  await Font.loadAsync({
    "boldfont": require('../../assets/fonts/SpaceGrotesk-Bold.ttf'),
    "regularfont": require('../../assets/fonts/SpaceGrotesk-Regular.ttf'),
    // 可在此添加更多字体
  });
};

export default loadFonts;

App.js

import { AppLoading } from 'expo';
import React, { useState, useEffect } from 'react';

import loadFonts from './src/screens/fontConfig';
const App = () => {
  const [fontsLoaded, setFontsLoaded] = useState(false);

  useEffect(() => {
    loadFonts().then(() => {
      setFontsLoaded(true);
    });
  }, []);

  return (
    <Onboarding3/>
  );
};

export default App;

运行时触发错误:

"boldfont is not a system font and has not been loaded through Font.loadAsync - If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system. If this is a custom font, be sure to load it with Font.loadAsync."

错误原因及修复方案

核心问题

组件<Onboarding3/>在字体加载完成前就被渲染了,导致组件使用boldfont时,字体资源尚未加载完毕。

具体修复步骤

  1. 用AppLoading控制渲染时机
    修改App.js的返回逻辑,确保字体加载完成后再渲染业务组件:

    const App = () => {
      const [fontsLoaded, setFontsLoaded] = useState(false);
    
      useEffect(() => {
        loadFonts().then(() => {
          setFontsLoaded(true);
        });
      }, []);
    
      // 字体未加载完成时显示加载状态
      if (!fontsLoaded) {
        return <AppLoading />;
      }
    
      return <Onboarding3/>;
    };
    
  2. 验证字体文件路径
    检查fontConfig.js中require('../../assets/fonts/xxx.ttf')的路径是否正确,路径层级要和文件实际位置匹配,避免因路径错误导致字体无法加载。

  3. 确认字体文件有效性
    确保SpaceGrotesk-Bold.ttf和SpaceGrotesk-Regular.ttf确实存在于assets/fonts目录下,文件名(包括大小写)要完全一致,避免拼写错误。

可选优化:添加错误处理

为loadFonts函数添加异常捕获,方便排查加载失败的具体原因:

const loadFonts = async () => {
  try {
    await Font.loadAsync({
      "boldfont": require('../../assets/fonts/SpaceGrotesk-Bold.ttf'),
      "regularfont": require('../../assets/fonts/SpaceGrotesk-Regular.ttf'),
    });
  } catch (err) {
    console.error('字体加载失败:', err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:57:23