首页 > 解决方案 > 在 react native 中添加自定义字体

问题描述

在我的 react-native 项目中添加一些自定义字体,我尝试了很多不同的方式,但每次我得到错误按摩:

错误 fontFamily "someFont" is not system font and has not been loaded through Font.loadAsync

我已经阅读了这个页面并尝试了这个方法: https ://docs.expo.io/guides/using-custom-fonts/

这是我的 package.json :

dependencies": {
    "@use-expo/font": "^2.0.0",
    "expo": "~40.0.0",
    "expo-font": "~8.4.0",
    "expo-status-bar": "~1.0.3",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
    "react-native-web": "~0.13.12"
  },

这是我的 app.js

import React from 'react';
import WelcomeScreen from "./app/screens/WelcomeScreen";
import ViewImageScreen from "./app/screens/ViewImageScreen";
import * as Font from "expo-font";
import FullyText from "./app/screens/FullyText";

export default function App() {
   const loadFont = () => {
        return Font.loadAsync({
            "someFont": require('./app/assets/fonts/IRANSans_Bold.ttf')
        })
    }

    return <FullyText/>
}

而我的 fullText 在另一页上:

import React from 'react';
import {Text} from "react-native";
import * as Font from "expo-font";

function FullyText(props) {

    return (
        <Text
        style={{
            top: 100,
            right: 10,
            fontFamily: "someFont",
             fontWeight: 'bold',
        }}>
Some random text
        </Text>
    );
}

export default FullyText;

标签: reactjsreact-nativereact-native-android

解决方案


最后我找到了为什么它不起作用,现在我要告诉我的解决方案,给任何可能陷入我的问题的人:

所以首先检查你是否安装了这些:

expo install expo-app-loading  

并像这样加载它:

import AppLoading from "expo-app-loading";

之后使用这种方式:首先安装:

   expo install @expo-google-fonts/raleway

请注意,我还像这样在我的项目中导入了 raleway google 字体

import {useFonts, Raleway_200ExtraLight} from "@expo-google-fonts/raleway";




export default function App() {
    let [fontLoaded, error] = useFonts({
        Raleway_200ExtraLight,

        "someFont": require("./assets/fonts/someFont.ttf"),
    })

    if (!fontLoaded){
      return <AppLoading/>
    }


    return (
        <View style={styles.container}>
            <Text style={
              {
                fontFamily: "Raleway_200ExtraLight",
                fontSize: 24,
              }
            }>Open up App.js to start working on your app!</Text>


    );
}

推荐阅读