在 React Native 中使用自定义字体

问题描述 投票:0回答:1

我是学习 React Native 的初学者,我正在尝试在我的应用程序中包含自定义字体(.ttf 文件)。

我收到这样的警告:

fontFamily "DMRegular" is not a system font and has not been loaded through expo-font

这是我在 _layout.js 文件中所做的:

import { Stack } from 'expo-router'
import { useCallback } from 'react'
import { useFonts } from 'expo-font'
import * as SplashScreen from 'expo-splash-screen'

SplashScreen.preventAutoHideAsync()

const Layout = () => {
    const [fontsLoaded] = useFonts({
        DMBold: require('../assets/fonts/DMSans-Bold.ttf'),
        DMRegular: require('../assets/fonts/DMSans-Regular.ttf'),
        DMMedium: require('../assets/fonts/DMSans-Medium.ttf'),
    })
    
    
    const onLayoutRootView = useCallback(async () => {
        if(fontsLoaded) {
            await SplashScreen.hideAsync();
        }
    }, [fontsLoaded])

    if(!fontsLoaded) return null;
    return <Stack onLayout={onLayoutRootView} />;
}

我正在尝试使用这样的自定义字体:

const styles = StyleSheet.create({
  welcomeMessage: {
    fontFamily: "DMBold",
    fontSize: SIZES.xLarge,
    color: COLORS.primary,
    marginTop: 2,
  }

请提供任何帮助,我们将不胜感激。

版本:

"expo": "~50.0.14"
"expo-font": "~11.10.3"

javascript react-native expo truetype
1个回答
0
投票

要使用 Expo 在 React Native 应用程序中包含自定义字体,您需要执行以下步骤:

导入 Expo 字体:确保在项目中导入 expo-font。

加载字体:在渲染任何使用自定义字体的 UI 组件之前,使用 Font.loadAsync() 加载自定义字体。

使用自定义字体:加载字体后,您可以通过指定 fontFamily 在样式中使用它们。

以下是在 _layout.js 文件中执行此操作的方法:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
import React, { useState } from 'react';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';

// Function to load custom fonts
const loadFonts = async () => {
  await Font.loadAsync({
    'DMRegular': require('./path/to/DMRegular.ttf'),
    // Add more fonts if needed
  });
};

const Layout = ({ children }) => {
  const [fontsLoaded, setFontsLoaded] = useState(false);

  if (!fontsLoaded) {
    return (
      <AppLoading
        startAsync={loadFonts}
        onFinish={() => setFontsLoaded(true)}
        onError={console.warn} // Handle error if font loading fails
      />
    );
  }

  // Render children when fonts are loaded
  return (
    <React.Fragment>
      {children}
    </React.Fragment>
  );
};

export default Layout;

  1. 我们定义一个 loadFonts 函数来加载我们的自定义字体 Font.loadAsync().
  2. 在 Layout 组件内部,我们使用 useState 来跟踪是否 字体已加载。
  3. 如果字体尚未加载,我们从 Expo 渲染 AppLoading, 显示加载屏幕,直到加载字体。
  4. 加载字体后,我们渲染子组件。
© www.soinside.com 2019 - 2024. All rights reserved.