react-native 异步函数钩子的问题
2019-07-07
2671
我尝试加载字体系列,我使用了带有异步函数的钩子,但出现了一些错误:
function Button(props: TouchableOpacityProps & ButtonProps) {
useEffect(() => {
async function loadFont() {
await Font.loadAsync({
gotham_medium: require("../../assets/GothamMedium_1.ttf")
});
}
loadFont()
}, []);
return (
<TouchableOpacity {...props} style={styles.button}>
<Text style={styles.title}>{props.title}</Text>
</TouchableOpacity>
);
};
我从 expo 导入了 Font,并从 react 导入了 useEffect,但出现了此错误。 设备出现错误
2个回答
这是我的应用程序上的内容,希望它能对某人有所帮助。
useEffect(() => {
const loadFonts = async () => {
await Font.loadAsync({
'pokeh': require('../../assets/fonts/pokeh.ttf'),
});
setFontReady(true);
};
loadFonts();
}, []);
使用 npm 安装 expo-font 后,最上面的这两个
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
在此树结构下:
Francislainy Campos
2020-03-20
您的错误可能是由错误的 React 版本生成的。您确定至少使用的是 Expo SDK 33 吗?
如果这不是问题所在,我相信如果您在流程早期加载所有资产可能会更容易。Expo 提供了一个
AppLoading
组件,它接受一个
startAsync
prop,可用于轻松解决所有异步承诺。
因此您的
App.js
可能看起来像:
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { StyleSheet, View, Text } from 'react-native';
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome to your Expo app</Text>
</View>
);
}
}
async function loadResourcesAsync() {
await Promise.all([
Font.loadAsync({
'gotham-medium': require('./assets/GothamMedium_1.ttf')
}),
]);
}
function handleLoadingError(error) {
console.warn(error);
}
function handleFinishLoading(setLoadingComplete) {
setLoadingComplete(true);
}
const styles = StyleSheet.create({
container: {
marginTop: 60,
flex: 1,
backgroundColor: '#fff',
},
title: {
fontFamily: 'gotham-medium',
fontSize: 36
}
});
然后您可以在应用程序的任何地方访问
fontFamily: 'gotham-medium'
。您还可以在
Promise.all()
调用中解决多个承诺
(加载其他资产等)
。
让我知道这是否有帮助。干杯!
Andrei Popa
2019-08-02