如何将自定义字体应用于整个项目,Expo React Native

lvjbypge  于 2023-01-27  发布在  React
关注(0)|答案(7)|浏览(218)

我是React和这些语言的新手。尝试将自定义的谷歌字体(Ubuntu)应用到整个项目。我设法将字体拉到项目中,但我只能在App.js中的简单文本中使用它。

import React, {useState} from 'react';
import './firebase/index';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { ThemeProvider } from 'react-native-elements';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { BLUE } from './common/colors';
import Dashboard from './screens/Dashboard';
import Login from './screens/Login';
import Accounts from './screens/Accounts';
import Cards from './screens/Cards';
import Credits from './screens/Credits';
import Insurances from './screens/Insurances';
import Investments from './screens/Investments';
import MoneyTransfers from './screens/MoneyTransfers';
import OtherOperations from './screens/OtherOperations';
import Payments from './screens/Payments';

import * as Font from "expo-font";
import Apploading from "expo-app-loading";
import { StyleSheet, Text, View } from "react-native";

const Drawer = createDrawerNavigator();

const getFonts = () =>
  Font.loadAsync({
    limelight: require("./assets/fonts/Ubuntu-Regular.ttf"),
    indie: require("./assets/fonts/Ubuntu-BoldItalic.ttf"),
  });

export default function App() {

  const [fontsloaded, setFontsLoaded] = useState(false);
  if (fontsloaded){
    return (
      <View>
          <Text 
            style={{ fontFamily: "limelight" }}>
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "limelight" }}>
             Hello World
          </Text>
          <Text 
            >
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "indie" }}>
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "limelight" }}>
             Hello World
          </Text>
          <Text 
            >
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "indie" }}>
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "indie" }}>
             Hello World
          </Text>
          <Text 
            >
             Hello World
          </Text>
          <Text 
            >
             Hello World
          </Text>
          <Text 
            style={{ fontFamily: "limelight" }}>
             Hello World
          </Text>
          <Text 
            >
             Hello World
          </Text>
        </View>
    );
  }
  else {
    return (
      <Apploading
        startAsync={getFonts}
        onFinish={() => {
          setFontsLoaded(true);
        }}
        onError={console.warn}
      />
    );
  }
  
}

但是我使用这些文本只是为了测试。在正常情况下,我的代码是这样的,当我尝试使用ubuntuRegular字体时,它不起作用。

import React, {useState} from 'react';
import './firebase/index';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { ThemeProvider } from 'react-native-elements';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { BLUE } from './common/colors';
import Dashboard from './screens/Dashboard';
import Login from './screens/Login';
import Accounts from './screens/Accounts';
import Cards from './screens/Cards';
import Credits from './screens/Credits';
import Insurances from './screens/Insurances';
import Investments from './screens/Investments';
import MoneyTransfers from './screens/MoneyTransfers';
import OtherOperations from './screens/OtherOperations';
import Payments from './screens/Payments';

import * as Font from "expo-font";
import Apploading from "expo-app-loading";
import { StyleSheet, Text, View } from "react-native";

const Drawer = createDrawerNavigator();

const getFonts = () =>
  Font.loadAsync({
    limelight: require("./assets/fonts/Ubuntu-Regular.ttf"),
    indie: require("./assets/fonts/Ubuntu-BoldItalic.ttf"),
  });

export default function App() {

  const [fontsloaded, setFontsLoaded] = useState(false);
  if (fontsloaded){
    return (
      <SafeAreaProvider>
        <ThemeProvider>
          <NavigationContainer>
            <Drawer.Navigator
              drawerType="slide"
              initialRouteName="Login"
              screenOptions={{
                headerShown: true,
                headerStyle: {
                  backgroundColor: BLUE,
                },
                headerTintColor: '#fff',
                headerTitleStyle: {
                  fontWeight: 'bold',
                  fontFamily: 'ubuntuRegular'
                },
              }}
            >
              {/* Dashboard a ayri header gecilebilir
              https://reactnavigation.org/docs/headers#replacing-the-title-with-a-custom-component */}
              <Drawer.Screen
                name="Login"
                component={Login}
                options={{ headerShown: false, title: 'Login' }}
              />
              <Drawer.Screen
                name="Dashboard"
                component={Dashboard}
                options={{ title: 'Anasayfa' }}
              />
              <Drawer.Screen
                name="Accounts"
                component={Accounts}
                options={{ title: 'Hesaplarım' }}
              />
              <Drawer.Screen
                name="Cards"
                component={Cards}
                options={{ title: 'Kartlarım' }}
              />
              <Drawer.Screen
                name="Money Transfers"
                component={MoneyTransfers}
                options={{ title: 'Para Transferleri' }}
              />
              <Drawer.Screen
                name="Investments"
                component={Investments}
                options={{ title: 'Yatırımlar' }}
              />
              <Drawer.Screen
                name="Payments"
                component={Payments}
                options={{ title: 'Ödemeler' }}
              />
              <Drawer.Screen
                name="Credits"
                component={Credits}
                options={{ title: 'Krediler' }}
              />
              <Drawer.Screen
                name="Insurances"
                component={Insurances}
                options={{ title: 'Sigortalar' }}
              />
              <Drawer.Screen
                name="Other Operations"
                component={OtherOperations}
                options={{ title: 'Diğer İşlemler' }}
              />
            </Drawer.Navigator>
          </NavigationContainer>
        </ThemeProvider>
      </SafeAreaProvider>
    );
  }
  else {
    return (
      <Apploading
        startAsync={getFonts}
        onFinish={() => {
          setFontsLoaded(true);
        }}
        onError={console.warn}
      />
    );
  }
  
}

此外,我如何在App.js之外使用此字体,就像我有一个MenuTitle组件一样:

import React, {useState} from 'react';
import { StyleSheet, Text } from 'react-native';
import * as Font from "expo-font";
import Apploading from "expo-app-loading";

const getFonts = () =>
  Font.loadAsync({
    limelight: require("../assets/fonts/Ubuntu-Regular.ttf"),
    indie: require("../assets/fonts/Ubuntu-BoldItalic.ttf"),
  });

const MenuTitle = ({ text, textStyles = {} }) => {
  
  return <Text style={[styles.title, textStyles]}>{text}</Text>;
};

export default MenuTitle;

const styles = StyleSheet.create({
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    paddingHorizontal: 20,
    fontFamily: 'ubuntuRegular'
  },
});

而且这也不起作用。如果你能帮忙,我会很高兴的。

ruarlubt

ruarlubt1#

创建一个名为hooks的文件夹,在其中存放App.js,然后在hooks文件夹中创建一个名为useFonts.js的文件
useFonts.js中,如下所示

import * as Font from 'expo-font';

export default useFonts = async () =>
  await Font.loadAsync({
    limelight: require('../assets/fonts/Ubuntu-Regular.ttf'),
    indie: require('../assets/fonts/Ubuntu-BoldItalic.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}>{/* Rest of the Code Here */}</View>;
}
6rvt4ljy

6rvt4ljy2#

1.将字体资源添加到项目文件夹exp assets/fonts
1.创建变量字体exp customFonts
1.在App.js上导入,如下所示

import AppLoading from 'expo-app-loading';
import { useFonts } from 'expo-font';
let customFonts = {
  'Poppins-Black': require('./assets/fonts/Poppins-Black.ttf')
};

const App = () => {
  const [isLoaded] = useFonts(customFonts);
  if (!isLoaded) {
    return <AppLoading />;
  }
    return <RootApp />;
}
cs7cruho

cs7cruho3#

将.ttf添加到资产后,您是否尝试过执行以下步骤/font:

  • 在根项目目录中创建配置文件react-native.config.js,并添加以下代码:
module.exports = {
     project: {
         ios: {},
         android: {},
     },
     assets: ['./App/assets/fonts'],
 };
  • 通过运行以下命令链接新添加的资源:
yarn react-native link

react-native link

如果一切正常,您可以在android/app/src/main/assets/fonts中看到新的字体资源,在iOS中可以在Info.plist中看到更改。
最后,重新运行应用程序
在此之后,您可以将您的字体样式放在样式文件中,然后在所有项目中使用它们:

bold11: {
    color: Colors.black,
    fontSize: 11,
    fontFamily: 'Roboto-Bold',
},
regular14: {
    color: Colors.black,
    fontFamily: 'Roboto-Regular',
    fontSize: 14,
},
idv4meu8

idv4meu84#

    • 应用程序js**
export default class App extends React.Component{
  constructor(props) {
      super(props)

      this.state = {
          fontsLoaded: false,
      }
  }
  async loadFont(){
      await Font.loadAsync({
          'ABeeZee-Italic' : require('./assets/fonts/ABeeZee-Italic.ttf'),
          'ABeeZee-Regular' : require('./assets/fonts/ABeeZee-Regular.ttf'),
      });
      this.setState({fontsLoaded:true});
  }

  componentDidMount(){
      this.loadFont();
  }
  render(){
         if(this.state.fontsLoaded)
             return Your_Component;
         else
             return AppLoading_Component;
          }

添加代码如上所示,然后你可以使用字体在任何网页上喜欢如下。

<Text style={{fontFamily: 'ABeeZee-Regular'}}> This is ABeeZee Regular Font</Text>
5cnsuln7

5cnsuln75#

使用Expo,您通常可以通过两种不同的方式将自定义字体应用于项目:
第一种方法是使用@expo-google-fonts/* 软件包,简单地安装该软件包,如下所示:
yarn add @expo-google-fonts/蒙特塞拉特(安装蒙特塞拉特字体)
然后在你的代码中

import React from "react";
import { View, Text } from "react-native";
import {
    useFonts,
    Montserrat_400Regular,
    Montserrat_400Regular_Italic,
    Montserrat_900Black,
} from "@expo-google-fonts/montserrat";
import AppLoading from "expo-app-loading";

export default function App() {
    const [loadedFonts] = useFonts({
        Regular: Montserrat_400Regular,
        Italic: Montserrat_400Regular_Italic,
        Black: Montserrat_900Black,
    });

    if (!loadedFonts) {
        return <AppLoading />;
    }

    return (
        <View style={{ flex: 1, justifyContent: "center" }}>
            <Text style={{ fontFamily: "Regular", fontSize: 32 }}>Hello</Text>
        </View>
    );
}

使用此目录获取更多帮助:https://directory.vercel.app/
useFont钩子处理其他应答中显示的Font.loadAsync逻辑。
第二种方法是在本地导入字体。

import React from "react";
import { View, Text } from "react-native";
import { useFonts } from "expo-font";
import AppLoading from "expo-app-loading";

export default function App() {
    const [loadedFonts] = useFonts({
        Regular: require("./assets/fonts/Montserrat-Regular.ttf"),
    });

    if (!loadedFonts) {
        return <AppLoading />;
    }

    return (
        <View style={{ flex: 1, justifyContent: "center" }}>
            <Text style={{ fontSize: 32, fontFamily: "Regular" }}>Hello</Text>
        </View>
    );
}

小提示:

如果你使用的是最新的SDK 45,expo-app-loading已经过时了,应该用expo-splash-screen来代替,Expo docs可以帮你解决这个问题。

isr3a4wc

isr3a4wc6#

使用Font.loadAsync而不是useFonts挂接如果不想使用useFonts挂接。

(for example, maybe you prefer class components), you can use Font.loadAsync directly. Under the hood, the hook uses Font.loadAsync from the expo-font library. You can use it directly if you prefer, or if you want to have more fine-grained control over when your fonts are loaded before rendering.

import React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    import * as Font from 'expo-font';
    
    let customFonts = {
      'Inter-Black': require('./assets/fonts/Inter-Black.otf'),
      'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
    };
    
    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 null;
        }
    
        return (
          <View style={styles.container}>
            <Text style={{ fontFamily: 'Inter-Black', fontSize: 30 }}>Inter Black</Text>
            <Text style={{ fontFamily: 'Inter-SemiBoldItalic', fontSize: 30 }}>
              Inter SemiBoldItalic
            </Text>
            <Text style={{ fontSize: 30 }}>Platform Default</Text>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({ ... });
6ie5vjzr

6ie5vjzr7#

有了expo,你可以通过使用'expo-google-fonts' liabrary直接使用谷歌字体。

安装命令npx expo安装expo-font @expo-google-fonts/inter
使用Google字体

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useFonts, Inter_900Black } from '@expo-google-fonts/inter';

export default function App() {
  let [fontsLoaded] = useFonts({
    Inter_900Black,
  });

  if (!fontsLoaded) {
    return null;
  }

  return (
    <View style={styles.container}>
      <Text style={{ fontFamily: 'Inter_900Black', fontSize: 40 }}>Inter Black</Text>
    </View>
  );
}

获取更多帮助访问Expo Docs Expo谷歌字体

相关问题