React Native用AppLoading加载自定义字体报type invalid错误如何解决
报错原因
expo-app-loading包的AppLoading组件为默认导出,你的代码使用了命名导入的写法,导致导入结果为undefined,触发组件类型无效报错。onFinish回调未执行状态更新逻辑,只写了函数引用没有调用setFontsLoaded,无法完成加载状态切换。
修复方案
- 修正导入语句,将命名导入改为默认导入:
// 修改前 // import { AppLoading } from 'expo-app-loading'; // 修改后 import AppLoading from 'expo-app-loading';
- 修正
onFinish回调逻辑,执行状态更新,同时补充onError回调捕获加载异常:
// 修改前 // return <AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded} /> // 修改后 return <AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} onError={(err) => console.log('字体加载失败', err)} />
如果你使用的是Expo SDK 46及以上版本,AppLoading已经被官方弃用,可以直接使用expo-font提供的useFonts钩子简化逻辑,无需额外引入expo-app-loading:
import React from 'react'; import { useFonts } from 'expo-font'; import Home from './screens/Home'; export default function App() { const [fontsLoaded] = useFonts({ 'nunito-regular': require('./assets/Fonts/Nunito-Regular.ttf'), 'nunito-bold': require('./assets/Fonts/Nunito-Bold.ttf'), }); if (!fontsLoaded) { return null; } return <Home />; }
内容的提问来源于stack exchange,提问作者Alexandre Carneiro da Silva
相关产品推荐
相关产品推荐

