问题
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