我是学习 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"
要使用 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;