在 React Native 中加载自定义字体时出错
Loading custom fonts in React Native is giving error
fontFamily "pro"不是系统字体,还没有通过Font.loadAsync加载。
- 如果您打算使用系统字体,请确保您输入的名称正确并且您的设备操作系统支持该名称。
- 如果这是自定义字体,请务必使用 Font.loadAsync 加载它。
但如果我消除错误,我会看到字体已加载。
这是我的代码:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {loading: true};
}
async componentDidMount() {
await Font.loadAsync({
pro: require('./assets/fonts/MavenPro-Regular.ttf'),
medium: require('./assets/fonts/MavenPro-Medium.ttf'),
}).then(() => {
this.setState({loading: false});
});
}
render() {
return (
<Provider store={store}>
<NavigationContainer>
{
<Drawer.Navigator
drawerType={'slide'}
drawerContent={(props) => <DrawerContent {...props} />}>
<Drawer.Screen
name="Home"
component={HomeStackScreen}
options={{
swipeEnabled: false,
}}
/>
</Drawer.Navigator>
}
</NavigationContainer>
</Provider>
);
}
}
您没有根据加载状态延迟呈现应用程序,因此您在字体加载之前呈现应用程序,因此出现错误。
注意 this example 中 AppLoading
组件是在加载字体时呈现的,您可以根据需要使用它,或者您想要显示的任何其他内容。
此外,与您的问题无关,但如果您使用 await
,则不需要使用 then()
await doSomething();
this.setState({ done: true });
fontFamily "pro"不是系统字体,还没有通过Font.loadAsync加载。
- 如果您打算使用系统字体,请确保您输入的名称正确并且您的设备操作系统支持该名称。
- 如果这是自定义字体,请务必使用 Font.loadAsync 加载它。
但如果我消除错误,我会看到字体已加载。
这是我的代码:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {loading: true};
}
async componentDidMount() {
await Font.loadAsync({
pro: require('./assets/fonts/MavenPro-Regular.ttf'),
medium: require('./assets/fonts/MavenPro-Medium.ttf'),
}).then(() => {
this.setState({loading: false});
});
}
render() {
return (
<Provider store={store}>
<NavigationContainer>
{
<Drawer.Navigator
drawerType={'slide'}
drawerContent={(props) => <DrawerContent {...props} />}>
<Drawer.Screen
name="Home"
component={HomeStackScreen}
options={{
swipeEnabled: false,
}}
/>
</Drawer.Navigator>
}
</NavigationContainer>
</Provider>
);
}
}
您没有根据加载状态延迟呈现应用程序,因此您在字体加载之前呈现应用程序,因此出现错误。
注意 this example 中 AppLoading
组件是在加载字体时呈现的,您可以根据需要使用它,或者您想要显示的任何其他内容。
此外,与您的问题无关,但如果您使用 await
then()
await doSomething();
this.setState({ done: true });