求助:Expo中‘Roboto-Black’非系统字体错误及await/Promise使用问题
解决 "Roboto-Black" 不是系统字体的错误
嘿,别担心!这个问题在使用Create React Native App(CRNA)和Expo时特别常见,我一步步带你搞定它~
问题原因
错误提示"Roboto-Black" is not a system font的意思很明确:Roboto-Black并不是iOS/Android系统默认预装的字体,所以我们得手动把它加载到应用里,而Expo.Font.loadAsync()就是干这个的核心工具。而且必须等字体加载完成后再渲染界面,不然就会触发报错。
具体修改步骤(结合你的代码)
假设你的组件开头是import React, { Component }...,我们把代码改成下面这样,每一步都有注释:
import React, { Component } from 'react'; import { View, Text, StyleSheet } from 'react-native'; // 必须导入Expo的Font和AppLoading模块 import { Font, AppLoading } from 'expo'; export default class YourAppComponent extends Component { // 用状态标记字体是否加载完成 state = { fontsLoaded: false, }; // 组件挂载后异步加载字体 async componentDidMount() { // 调用Font.loadAsync加载我们需要的字体 await Font.loadAsync({ // 键是我们要引用的字体名称,值是字体文件的路径 // 注意:你需要把Roboto-Black.ttf放到项目的assets/fonts文件夹里(没有就新建) 'Roboto-Black': require('./assets/fonts/Roboto-Black.ttf'), }); // 字体加载完成后,更新状态让界面渲染 this.setState({ fontsLoaded: true }); } render() { // 如果字体还没加载好,先显示加载动画(AppLoading是Expo自带的) if (!this.state.fontsLoaded) { return <AppLoading />; } // 字体加载完成后,正常渲染你的界面,放心使用Roboto-Black字体 return ( <View style={styles.container}> <Text style={{ fontFamily: 'Roboto-Black', fontSize: 28 }}> 现在可以正常显示Roboto-Black字体啦! </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, });
几个关键注意点
- 字体文件路径要正确:确保
Roboto-Black.ttf确实在./assets/fonts/这个路径下(如果你的字体放在别的地方,对应修改require里的路径)。 - 多字体加载:如果需要加载多个字体,直接在
Font.loadAsync里添加键值对就行:await Font.loadAsync({ 'Roboto-Black': require('./assets/fonts/Roboto-Black.ttf'), 'Roboto-Regular': require('./assets/fonts/Roboto-Regular.ttf'), }); - Promise替代写法:如果你暂时不太理解
async/await,也可以用Promise的.then()写法,效果一样:componentDidMount() { Font.loadAsync({ 'Roboto-Black': require('./assets/fonts/Roboto-Black.ttf'), }).then(() => { this.setState({ fontsLoaded: true }); }); }
只要按照上面的步骤改,你的字体错误应该就能解决啦!如果还有问题,检查下字体文件名、路径有没有拼写错误~
内容的提问来源于stack exchange,提问作者Ray Jonathan
相关产品推荐
相关产品推荐

