Can't seem to load custom fonts with Expo's Font.loadAsync

安稳与你 提交于 2019-12-14 02:19:32

问题


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'
  }, 

All I get is

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.

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

Am I missing something?


回答1:


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 (
        ...
    )
}


来源:https://stackoverflow.com/questions/52917558/cant-seem-to-load-custom-fonts-with-expos-font-loadasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!