React Native Expo自定义字体加载失败,寻求技术解决方法
Hey there, I see exactly where the issue is—your app is trying to render the login screen before the custom font finishes loading. Let's fix this step by step:
You're loading the font asynchronously in componentDidMount, but your render method immediately returns the RootStack without waiting for the fontLoaded state to flip to true. This means the login screen renders while the font is still being fetched, hence the error.
1. Add a loading state check in your App component
Wait until the font is fully loaded before rendering your navigation stack. You can show a simple loading indicator in the meantime:
2. Verify font path and naming
Double-check that your font file exists at ./src/assets/fonts/OpenSans-Bold.ttf, and that the filename matches exactly (case sensitivity matters on some systems—don't mix OpenSans-Bold.ttf with opensans-bold.ttf).
import React from 'react'; import { View, ActivityIndicator, Platform, NativeModules } from 'react-native'; import { Expo } from 'expo'; import { StackNavigator } from 'react-navigation'; import LoginScreen from './src/views/LoginScreen'; import AuthenticatedScreen from './src/views/AuthenticatedScreen'; import './ReactotronConfig' const { StatusBarManager } = NativeModules; const RootStack = StackNavigator( { Login: { screen: LoginScreen }, Authenticated: { screen: AuthenticatedScreen } }, { initialRouteName: 'Login'} ); export default class App extends React.Component { state = { fontLoaded: false, }; async componentDidMount() { try { await Expo.Font.loadAsync({ 'open-sans-bold': require('./src/assets/fonts/OpenSans-Bold.ttf'), }); console.log('Custom font loaded successfully!') this.setState({ fontLoaded: true }); } catch (error) { console.error('Failed to load font:', error); } } render() { // Show loader until font is ready if (!this.state.fontLoaded) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <ActivityIndicator size="large" color="#0000ff" /> </View> ); } return <RootStack />; } } console.disableYellowBox = true;
- If you're using Expo SDK 38+,
Expo.Fonthas moved to theexpo-fontpackage. You'll need to runexpo install expo-font, then import it asimport * as Font from 'expo-font'and useFont.loadAsync(...)instead. - Make sure the font name
'open-sans-bold'in your login screen'sTextcomponent matches exactly the key you used inloadAsync(no typos, same casing).
This should resolve the font loading error and let you use your custom font properly!
内容的提问来源于stack exchange,提问作者tmehta2442

