向 React Native 应用程序添加自定义字体 - 版本 > 0.60

IT技术 android ios reactjs react-native
2021-05-07 03:04:15

我正在使用 React Native (V-0.64)。我使用了在assets文件夹中下载和添加自定义字体并创建一个react-native.config.js文件并从那里导出链接的方法。但是当我在设备上运行应用程序时,我不断收到以下错误。文件中的代码

module.exports = {
  assets: ['./assets/fonts'],
};

然后运行将npx react-native link资产链接到 android 和 iOS 文件。但是我在行中不断收到以下错误并且没有在文本中获得字体更改

fontFamily "VeganStylePersonalUse-5Y58" 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.
at node_modules/expo-font/build/Font.js:27:16 in processFontFamily
at [native code]:null in commitRootImpl
at [native code]:null in performSyncWorkOnRoot
at [native code]:null in forEach
at node_modules/react-native/Libraries/Core/setUpReactRefresh.js:43:6 in Refresh.performReactRefresh
at [native code]:null in callFunctionReturnFlushedQueue

我尝试了很多东西,但没有奏效。请帮忙。

1个回答

为了loadFonts这一点我在我所有的项目是创建一个文件夹,名为hooks在您App.js所在

然后,安装expo-app-loading&expo-font

然后在hooks文件夹内创建一个名为useFonts.js

里面这样useFonts.js

import * as Font from "expo-font";

export default useFonts = async () => {
   await Font.loadAsync({
      "Montserrat-Bold": require("../assets/fonts/Montserrat-Bold.ttf"),
    });
};.

现在在你这样App.js

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

import useFonts from './hooks/useFonts';

export default function App() {
  const [IsReady, SetIsReady] = useState(false);

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

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

  return <View styles={styles.container}>{/* Code Here */}</View>;
}