且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 expo 项目中加载自定义字体时出错

更新时间:2022-12-11 11:04:00

这里的工作示例

首先,运行 npm i expo-font

然后,运行 npm i @expo-google-fonts/open-sans

然后,运行 npm i expo-app-loading

然后在您的项目文件夹中创建一个名为 hooks 的文件,您的 App.js 所在的位置.

Then in your project folder create a file called hooks where your App.js is located.

hooks 文件夹中创建一个名为 useFonts.js 的文件并在其中粘贴此代码

in hooks folder create a file called useFonts.js and inside that paste this code

import * as Font from 'expo-font';

const useFonts = async () => {
  await Font.loadAsync({
    Montserrat: require('../assets/fonts/Mulish.ttf'),
  });
};

export default useFonts;

您的 App.js 应如下所示

import React, { Component, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AppLoading from 'expo-app-loading'; // This is must

import useFonts from './hooks/useFonts';

import LoginScreen from './assets/screens/LoginScreen';
import RegisterScreen from './assets/screens/RegisterScreen';

const Stack = createStackNavigator();

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

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

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

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Login"
        screenOptions={{
          headerShown: false,
        }}>
        <Stack.Screen name="Login" component={LoginScreen} />
        <Stack.Screen name="Register" component={RegisterScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

你的 LoginScreen.js 应该是这样的

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

function LoginScreen(props) {
  return (
    <View style={styles.container}>
      <Text style={{ fontFamily: 'Montserrat', fontSize: 30 }}>
        LoginScreen with fontFamily
      </Text>
      <Text style={{ fontSize: 30 }}>LoginScreen without fontFamily</Text>
    </View>
  );
}

export default LoginScreen;

const styles = StyleSheet.create({
  container: {},
});

这是加载字体的***方式,我在所有项目中都这样做.

This is the best way to load fonts and I do it like this in all my projects.