似乎无法使用 Expo 的 Font.loadAsync 加载自定义字体 [英] Can't seem to load custom fonts with Expo's Font.loadAsync

查看:20
本文介绍了似乎无法使用 Expo 的 Font.loadAsync 加载自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 React Native 与 Expo 结合使用,除了自定义字体的这个问题外,一切都很顺利.我在 ./assets/fonts 中有我的字体 Lobster-Regular.ttf,我一直在尝试加载它,如官方文档中所示:

I'm using React Native with Expo, and it is all going well except for this one issue with custom fonts. I have my font Lobster-Regular.ttfin ./assets/fonts, and I have been trying to load it as seen in the official docs:

componentDidMount() {

    Font.loadAsync({

      'Lobster': require('./assets/fonts/Lobster-Regular.ttf'),
    });

  }

然后我将我的标题设置为:

I then style my header as such:

  headerText: {
    color: 'white',
    fontSize: 30,
    fontFamily: 'Lobster'
  }, 

我得到的只是

fontFamily 'Lobster' 不是系统字体,尚未加载通过 Font.loadAsync.

fontFamily 'Lobster' is not a system font and has not been loaded through Font.loadAsync.

  • 如果您打算使用系统字体,请确保您输入的名称正确且受您的设备操作系统支持.

  • If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.

如果这是自定义字体,请务必使用 Font.loadAsync 加载它.

If this is a custom font, be sure to load it with Font.loadAsync.

我错过了什么吗?

推荐答案

是的.您错过了调用是 Font.loadAsync().这意味着它异步加载.如:这需要一段时间.在字体加载之前,您无法渲染 UI.您需要按照以下方式做一些事情:

Yes. You are missing that the call is Font.loadAsync(). This means that it loads asynchronously. As in: It takes a while. You can't render the UI until the font has loaded. You need to do something along these lines:

import { AppLoading, Font } from 'expo'

state = {
    fontsLoaded: false,
    ...
}

componentWillMount() {
    Font.loadAsync( {
            'Lobster': require('./assets/fonts/Lobster-Regular.ttf')
        }
    ).then( () => this.setState( { fontsLoaded: true } ) )
}

render() {
    if( !this.state.fontsLoaded ) {
        return <AppLoading/>
    }

    return (
        ...
    )
}

这篇关于似乎无法使用 Expo 的 Font.loadAsync 加载自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆