如何使用 React Navigation 和 Redux 在 Expo 应用程序中加载自定义字体 [英] How to load custom Fonts in an Expo app using React Navigation and Redux

查看:30
本文介绍了如何使用 React Navigation 和 Redux 在 Expo 应用程序中加载自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I just can not load custom fonts in an existing app using Expo, React Natvigation. I have an app that has Navigations set up in a core.js file as

    import React from "react";
import {Text, View, StyleSheet} from "react-native";
import {NavigationContainer} from "@react-navigation/native";
import {createStackNavigator} from "@react-navigation/stack";
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import LoginScreen from "./login.js";
import RegisterScreen from "./register.js";
//import Home from "./home.js";
import PostAJobPage from "./secondTab.js";
import Ionicons from "react-native-vector-icons/Ionicons"
import store from "./store";
import SplashScreen from "./splashscreen";
import Home from "./homeStack.js";
import { Entypo } from '@expo/vector-icons';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import SearchAJobStack from "./jobsearchstack.js";


const Tab = createBottomTabNavigator()

const Tabs = () => {
  return(
    //<NavigationContainer>
      <Tab.Navigator initialRouteName = "home"
        screenOptions = {({route}) => ({
          tabBarIcon : ({focused,color, size}) => {
            let iconName;
            if(route.name == "home") {
              iconName = "ios-home"
              return <Ionicons name = {iconName} color = {color} size = {size}/>
            }
            else if(route.name == "postJob")
            {
              //iconName = "md-settings"
              iconName = "briefcase"
              return <Entypo name = {iconName} color = {color} size = {size}/>
            }
            else if (route.name == "searchJob")
            {
              iconName = "briefcase-search"
              return <MaterialCommunityIcons name = {iconName} size={size} color= {color} />
            }

            //return <Ionicons name = {iconName} color = {color} size = {size}/>
          }
        })}
        tabBarOptions = {{
          style : {
            height : 50
          },
          showLabel : false,
          activeTintColor : "gold"
        }

        }>
        <Tab.Screen name="home" component ={Home}/>
        <Tab.Screen name="postJob" component ={PostAJobPage}/>
        <Tab.Screen name="searchJob" component ={SearchAJobStack}/>
      </Tab.Navigator>
    //</NavigationContainer>
  )
}


const Stack = createStackNavigator()

function Stacks() {
  return(
    <NavigationContainer>
      <Stack.Navigator initialRouteName = "loadingPage">
        <Stack.Screen
          name = "loadingPage"
          component = {SplashScreen}
          options = {{
            headerShown : false
          }}/>

        <Stack.Screen
          name ="Main"
          component = {Tabs}
          options = {{
            headerShown : false,
          }}/>
        <Stack.Screen name= "login"
          component = {LoginScreen}
          options = {{
            title : "Login",
            headerTitleAlign : "left"
          }}/>

        <Stack.Screen name= "register"
          component = {RegisterScreen}
          options = {{
            title : "Register",
            headerTitleAlign : "left",
          }}/>
      </Stack.Navigator>
    </NavigationContainer>
  )
}

export default class core extends React.Component {

  render(){
    return (
      <Stacks/>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor : "#fff",
    alignItems : "center",
    justifyContent : "center",
  }
})

I am importing this stacks in my App.js and have added the code to add custom fonts according to the Docs in Expo but if I change fontFamily: Pacifico to any of the screens it doesnot work

My app.js file is

    import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Core from "./core.js";
import {Provider} from "react-redux";
import store from "./store.js";
import * as Font from "expo-font";

const customFonts = {
  dancingScript : require("./assets/fonts/DancingScript-Regular.ttf"),
  Pacifico : require("./assets/fonts/Pacifico-Regular.ttf"),
  Inter : require("./assets/fonts/Inter-VariableFont.ttf"),
}


export default class App extends React.Component {
  state = {
    fontsLoaded : false,
  }
  async _loadFontsAsync() {
    await Font.loadAsync(customFonts);
    this.setState({ fontsLoaded: true });
  }

  componentDidMount() {
    this._loadFontsAsync();
  }

  render(){
    if(this.state.fontsLoaded)
    {
      return (
        <Provider store = {store}>
          
          <Core/>

        </Provider>
      );
    }
    else {
      return(
        <View style= {styles.container}>
          <Image source = {require("./ajax-loader.gif")}/>
        </View>
      )
    }

  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    //fontFamily : "dancingScript",
  },
});

解决方案

I personally feel this is a better way to load custom fonts. I use this method in all my projects. To loadFonts create a folder called hooks where your App.js is located

Then, Install expo-app-loading & expo-font

Then inside hooks folder create a file called useFonts.js

Inside useFonts.js write like this

import * as Font from "expo-font";

export default useFonts = async () => {
   await Font.loadAsync({
      "Pacifico" : require("./assets/fonts/Pacifico-Regular.ttf"),
      // All other fonts here
    });
};.

Now in your App.js write like this

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>;
}

Note: The above solution was for Function components.

For Class Component, you can do something like this

Working Example Here

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

import useFonts from './hooks/useFonts';

export default class App extends React.Component {
  state = {
    fontsLoaded: false,
  };

  async _loadFontsAsync() {
    await useFonts();
    this.setState({ fontsLoaded: true });
  }

  componentDidMount() {
    this._loadFontsAsync();
  }

  render() {
    if (this.state.fontsLoaded) {
      return (
        <View style={styles.container}>
          <Text>Fonts Loaded</Text>
          <Text style={{ fontFamily: 'Helvetica' }}>Helvetica Text</Text>
          <Text>Normal Text</Text>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <Image
            source={{
              uri:
                'https://landerapp.com/blog/wp-content/uploads/2018/06/1_FFP1bisztXseQFbZ-WQedw-1.png',
            }}
            style={{ width: '100%', height: '100%' }}
          />
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    //fontFamily : "dancingScript",
  },
});

这篇关于如何使用 React Navigation 和 Redux 在 Expo 应用程序中加载自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆