我目前正在尝试向 React Native 应用程序添加自定义字体,但在尝试了我在 SO 和 google 上找到的几乎所有答案后,它仍然不起作用。
我尝试通过添加让 native react 识别字体
"rnpm": {
"assets": [
"./assets/fonts/"
]
},
到package.json
,然后运行react-native link
并使用re-run
命令。但还是不行。
下面是代码
app.js
import React, { useEffect } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import imager from './assets/cars.png';
import * as Font from 'expo-font';
export default function App() {
useEffect(() => {
async function loadFont() {
return await Font.loadAsync({
righteous: require('./assets/fonts/Righteous-Regular.ttf'),
});
}
loadFont();
}, []);
return (
<View style={styles.container}>
<Image style={styles.imager} source={imager} />
<Text
style={{
fontSize: 30,
fontWeight: 'bold',
paddingTop: 30,
fontFamily: 'righteous',
}}
>
Request Ride
</Text>
<Text style={{ fontSize: 15, padding: 40, textAlign: 'center' }}>
Request a ride and get picked up by a nearby community driver
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
imager: {
width: 200,
height: 200,
shadowColor: 'rgba(0, 0, 0, 0.2)',
shadowRadius: 10,
shadowOpacity: 1,
},
});
我在 ./assets/fonts
中有字体 Righteous-Regular.ttf
,但是当我运行此代码时,出现此错误
fontFamily "righteous" 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.
我进行了研究,但仍然找不到解决方案。请问这可能是什么问题,我该如何解决?
最佳答案
您正在尝试在加载字体之前使用该字体。你需要做这样的事情。
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import imager from './assets/cars.png';
import * as Font from 'expo-font';
export default function App() {
// use state for font status.
const [isFontReady, setFontReady] = useState(false)
useEffect(() => {
async function loadFont() {
return await Font.loadAsync({
righteous: require('./assets/fonts/Righteous-Regular.ttf'),
});
}
// after the loading set the font status to true
loadFont().then(() => {
setFontReady(true)
});
}, []);
return (
<View style={styles.container}>
<Image style={styles.imager} source={imager} />
{/* render the text after loading */}
{isFontReady && <Text
style={{
fontSize: 30,
fontWeight: 'bold',
paddingTop: 30,
fontFamily: 'righteous',
}}
>
Request Ride
</Text>}
<Text style={{ fontSize: 15, padding: 40, textAlign: 'center' }}>
Request a ride and get picked up by a nearby community driver
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
imager: {
width: 200,
height: 200,
shadowColor: 'rgba(0, 0, 0, 0.2)',
shadowRadius: 10,
shadowOpacity: 1,
},
});
您可以选择在安装字体后显示该元素,还是在安装字体之前使用不同的字体显示它。
关于javascript - 添加自定义字体系列以 react native 文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58459240/