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

React Native+NativeWind加载自定义OTF字体报错,求解决方案

解决React Native自定义OTF字体加载失败问题

问题核心

报错的根源是Tailwind配置中引用的字体名称与Font.loadAsync注册的字体key不匹配,同时useFonts函数存在语法错误,导致字体实际未完成加载。

具体调整步骤

1. 修正useFonts.js的函数声明与字体key

原函数定义语法不规范,且字体key需与Tailwind配置中的字体名称对齐:

import * as Font from "expo-font";

const useFonts = async () => {
  await Font.loadAsync({
    // 这里的key要和Tailwind配置里的字体名称完全一致
    "Pixel-Musketeer": require("../assets/fonts/Pixel-Musketeer.otf"),
  });
};

export default useFonts;

2. 同步Tailwind配置的字体族映射

确保tailwind.config.js中fontFamily的配置,别名与字体名称对应正确:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./App.{js,jsx,ts,tsx}",
    "./screens/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    colors: {
      mainRed: "#3B111D",
      grey: "#564950",
      darkGreen: "#86978F",
      green: "#BEDDA4",
      brightGreen: "#E4FABD",
    },
    extend: {
      fontFamily: {
        // "Musketeer"是你在className中使用的别名,对应字体名称要和loadAsync的key一致
        Musketeer: ["Pixel-Musketeer"],
      },
    },
  },
  plugins: [],
};

3. 完善字体加载的错误处理

在Home.js中添加错误捕获,避免加载失败后应用卡住:

import { View, Text } from "react-native";
import React, { useState } from "react";
import AppLoading from "expo-app-loading";
import useFonts from "../hooks/useFonts";

const Home = () => {
  const [IsReady, SetIsReady] = useState(false);

  const LoadFonts = async () => {
    try {
      await useFonts();
    } catch (error) {
      console.error("字体加载失败:", error);
    }
  };

  if (!IsReady)
    return (
      <AppLoading
        startAsync={LoadFonts}
        onFinish={() => SetIsReady(true)}
        onError={(error) => console.error("AppLoading错误:", error)}
      />
    );

  return (
    <View className="bg-mainRed flex-1 justify-center items-center">
      <Text className="font-Musketeer text-5xl">King's Dungeon</Text>
    </View>
  );
};

export default Home;

4. 验证字体文件路径

确认../assets/fonts/Pixel-Musketeer.otf路径正确:

  • 检查assets/fonts文件夹是否存在于对应层级(相对于useFonts.js的位置)
  • 字体文件名拼写完全一致,注意大小写(部分系统会区分文件名大小写)

额外检查项

  • 确保已安装依赖:执行npx expo install expo-font expo-app-loading
  • 重启Expo开发服务器,避免缓存导致的加载异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:55:28