【问题标题】:Expo Fonts loading incorrectlyExpo字体加载不正确
【发布时间】:2020-04-21 18:59:45
【问题描述】:
我正在使用 expo 字体加载字体,我突然遇到了一个新错误:“您开始加载字体,但在完成加载之前使用了它。”我不确定问题出在哪里。我尝试在应用程序中加载字体:
import * as Font from "expo-font";
export default class App extends React.Component {
async componentDidMount() {
await Font.loadAsync({
"open-sans-bold": require("./assets/Fonts/OpenSans-Bold.ttf")
});
}
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<StatusBar barStyle="dark-content" />
<AppContainer />
</View>
</Provider>
);
}
}
但是,错误仍然存在
【问题讨论】:
标签:
reactjs
react-native
expo
【解决方案1】:
出现错误是因为您在加载字体之前渲染了您的应用程序。你需要在它结束之前渲染另一个<View>。你可以修改你的代码:
import React from 'react-native';
import { Text, StyleSheet, View, ActivityIndicator } from 'react-native';
import * as Font from 'expo-font';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fontLoaded: false
};
}
async componentDidMount() {
await Font.loadAsync({
'open-sans-bold': require('./assets/Fonts/OpenSans-Bold.ttf')
}).then(() => {
// When the font is loaded you can rendered your app
this.setState({
fontLoaded: true
});
});
}
render() {
const { fontLoaded } = this.state;
// When your font is not loaded you display a Loading Component
if (!fontLoaded) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />;
</View>
);
} else {
return (
<Provider store={store}>
<View style={styles.container}>
<StatusBar barStyle="dark-content" />
<AppContainer />
</View>
</Provider>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignIems: 'center'
}
});