android 如何在react native with nativewind中使用自定义字体?

w1jd8yoj  于 2022-12-16  发布在  Android
关注(0)|答案(2)|浏览(105)

我是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.

我已经尝试使用字体.loadAsync,但得到这个错误在任何情况下。
我现在的代码:

主页. 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;

使用字体. js

import * as Font from "expo-font";

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

尾风配置文件js

/** @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: ["Pixel-Musketeer"],
      },
    },
  },
  plugins: [],
};


我应该删除或添加什么才能加载此字体?

m2xkgtsf

m2xkgtsf1#

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

export const FONTFAMILY = {
    musketeer: {fontFamily: 'Musketeer'},
}

然后在主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
  );
}
643ylb08

643ylb082#

如果尚未创建配置文件,请在名为react-native.config.js的项目的根目录下创建一个配置文件。然后在module.exports中添加以下代码:

相关问题