React Native:用useFonts加载自定义字体,替换废弃的AppLoading
要解决expo-app-loading弃用的警告,改用expo-splash-screen的API即可,以下是修改步骤和完整代码:
步骤1:确保安装expo-splash-screen
如果项目还没安装该依赖,运行命令:
npx expo install expo-splash-screen
步骤2:修改App.js代码
移除AppLoading相关代码,改用SplashScreen.preventAutoHideAsync()和SplashScreen.hideAsync()控制启动屏:
import React, { useEffect } from "react"; import { StyleSheet, Text, View } from "react-native"; import { useFonts } from "expo-font"; import * as SplashScreen from 'expo-splash-screen'; // 阻止启动屏自动隐藏 SplashScreen.preventAutoHideAsync(); export default function App() { const [fontsLoaded] = useFonts({ "Inter-Black": require("./assets/fonts/Inter-Black.ttf"), }); useEffect(() => { async function handleSplashScreen() { if (fontsLoaded) { // 字体加载完成后隐藏启动屏 await SplashScreen.hideAsync(); } } handleSplashScreen(); }, [fontsLoaded]); // 字体未加载完成时不渲染内容,启动屏会保持显示 if (!fontsLoaded) { return null; } return ( <View style={styles.container}> <Text style={[styles.textStyling, styles.textInterBlack]}> Inter Black </Text> <Text style={styles.textStyling}>Platform Default</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center" }, textStyling: { fontSize: 30 }, textInterBlack: { fontFamily: "Inter-Black" }, });
关键说明
- 初始化阶段调用
SplashScreen.preventAutoHideAsync(),避免启动屏提前消失 - 通过
useEffect监听字体加载状态,一旦加载完成就调用SplashScreen.hideAsync()隐藏启动屏 - 字体未就绪时返回
null,此时启动屏会持续显示,直到字体加载完成
内容的提问来源于stack exchange,提问作者Henke
相关产品推荐
相关产品推荐

