React Native 使用异步 componentDidMount() 预期导入字体 =>
React Native importing fonts with async componentDidMount() expected =>
我正在尝试为项目的标题导入字体,我正在加载字体:
import * as Font from 'expo-font'
const Home = () => {
return(
this.state = {
fontLoaded: false
}
async componentDidMount(){
await Font.loadAsync({
'Pacifico': require('../assets/pacifico/Pacifico.ttf'),
}).then(() => {
this.setState({fontLoaded: true})
})
<View style={{marginTop:30, alignItems:'center'}}>
{this.state.fontLoaded ? (<Text>Loading...</Text>): (
<Text style={{fontSize:40, fontFamily:'Pacifico'}}>Book Lover</Text>
)}
</View>
)}
然而,当我编译项目时,我收到一条错误消息
Unexpected token, expected "=>"
它指向 async componentDidMount(){
行
有什么我可以解决的吗?
如果你想使用带钩子的函数式组件,试试这样:
添加到进口:
import { useState, useEffect } from 'react';
和
const Home = () => {
const [fontLoaded, setFontLoaded] = useState(false);
useEffect(async() => {
await Font.loadAsync({
Pacifico: require('../assets/pacifico/Pacifico.ttf'),
});
setFontLoaded(true);
}, []);
return (
<View style={{ marginTop: 30, alignItems: 'center' }}>
{!fontLoaded ? (
<Text>Loading...</Text>
) : (
<Text style={{ fontSize: 40, fontFamily: 'Pacifico' }}>Book Lover</Text>
)}
</View>
);
};
我正在尝试为项目的标题导入字体,我正在加载字体:
import * as Font from 'expo-font'
const Home = () => {
return(
this.state = {
fontLoaded: false
}
async componentDidMount(){
await Font.loadAsync({
'Pacifico': require('../assets/pacifico/Pacifico.ttf'),
}).then(() => {
this.setState({fontLoaded: true})
})
<View style={{marginTop:30, alignItems:'center'}}>
{this.state.fontLoaded ? (<Text>Loading...</Text>): (
<Text style={{fontSize:40, fontFamily:'Pacifico'}}>Book Lover</Text>
)}
</View>
)}
然而,当我编译项目时,我收到一条错误消息
Unexpected token, expected "=>"
它指向 async componentDidMount(){
行
有什么我可以解决的吗?
如果你想使用带钩子的函数式组件,试试这样:
添加到进口:
import { useState, useEffect } from 'react';
和
const Home = () => {
const [fontLoaded, setFontLoaded] = useState(false);
useEffect(async() => {
await Font.loadAsync({
Pacifico: require('../assets/pacifico/Pacifico.ttf'),
});
setFontLoaded(true);
}, []);
return (
<View style={{ marginTop: 30, alignItems: 'center' }}>
{!fontLoaded ? (
<Text>Loading...</Text>
) : (
<Text style={{ fontSize: 40, fontFamily: 'Pacifico' }}>Book Lover</Text>
)}
</View>
);
};