如何在 React Native 和 NativeWind 中使用自定义字体?

Rus*_*tov 5 javascript android ios reactjs react-native

我是 React-Native 的新手,我在添加字体时遇到问题,我试图从 .otf 文件加载自定义字体,但出现错误:

fontFamily "Pixel-Musketeer" 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.
Run Code Online (Sandbox Code Playgroud)

我尝试使用 Font.loadAsync 但无论如何都会出现此错误。

我现在的代码:

主页.js

fontFamily "Pixel-Musketeer" 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.
Run Code Online (Sandbox Code Playgroud)

useFonts.js

import {
  View,
  Text
} from "react-native";
import React from "react";

// State
import {
  useState
} from "react";

// Fonts
import AppLoading from "expo-app-loading";
import useFonts from "../hooks/useFonts";

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

  const LoadFonts = async() => {
    await useFonts();
  };

  if (!IsReady)
    return ( <
      AppLoading startAsync = {
        LoadFonts
      }
      onFinish = {
        () => SetIsReady(true)
      }
      onError = {
        () => {}
      } >
      < /AppLoading>
    );

  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;
Run Code Online (Sandbox Code Playgroud)

Tailwind.config.js

import * as Font from "expo-font";

export default useFonts = async () =>
  await Font.loadAsync({
    Musketeer: require("../assets/fonts/Pixel-Musketeer.otf"),
  });
Run Code Online (Sandbox Code Playgroud)

为了加载此字体,我应该删除或添加什么?

Joh*_*ean 3

use/make theme.js,将其保存为常量,以便可以在整个应用程序上使用它:

export const FONTFAMILY = {
    musketeer: {fontFamily: 'Musketeer'},
}
Run Code Online (Sandbox Code Playgroud)

然后在你的主 App.js 中

import { useFonts } from 'expo-font';
import { FONTFAMILY } from './theme.js';

export default function App() {

  const [fontsLoaded] = useFonts({
    'Musketeer': require("../assets/fonts/Pixel-Musketeer.otf"),
  });

  if(!fontsLoaded) return null;

  return (
    <Text style={{...FONTFAMILY.musketeer}}>used fonts here</Text
  );
}
Run Code Online (Sandbox Code Playgroud)