我正在将React Native与Expo一起使用,并且一切正常,除了这一问题涉及自定义字体。我的字体pa_source_port_info
位于./assets/fonts中,并且我一直在尝试加载它,如官方文档所示:
Lobster-Regular.ttf
然后我将标题设置为这样:
componentDidMount() {
Font.loadAsync({
'Lobster': require('./assets/fonts/Lobster-Regular.ttf'),
});
}
我所能得到的是
fontFamily'Lobster'不是系统字体,尚未加载 通过Font.loadAsync。
如果要使用系统字体,请确保正确键入名称,并且设备操作系统支持该名称。
如果这是自定义字体,请确保使用Font.loadAsync加载它。
我想念什么吗?
答案 0 :(得分:1)
是的。您丢失了呼叫为Font.loadAsync()
的信息。这意味着它会异步加载 。如:需要一段时间。在加载字体之前,无法渲染UI。您需要按照以下步骤进行操作:
import { AppLoading, Font } from 'expo'
state = {
fontsLoaded: false,
...
}
componentWillMount() {
Font.loadAsync( {
'Lobster': require('./assets/fonts/Lobster-Regular.ttf')
}
).then( () => this.setState( { fontsLoaded: true } ) )
}
render() {
if( !this.state.fontsLoaded ) {
return <AppLoading/>
}
return (
...
)
}
答案 1 :(得分:1)
**无状态函数**中的react-native字体
**步骤:1从博览会**导入字体
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
*步骤2:需要文件中的字体*
// fetchFonts from local files type ttf
const fetchFonts = () => {
return Font.loadAsync({
'PacificoRegular': require('../assets/Pacifico/Pacifico-Regular.ttf'),
});
};
*****step3:use state *****
// state font fetch control
const [fontloaded,setfontloaded]=useState(false);
**步骤4:使用已加载的应用程序**
if(!fontloaded){
return(
<AppLoading
startAsync={fetchFonts}
onFinish={()=>{setfontloaded(true)}}
onError={console.warn}/>
)
}
**第5步:样式字体**
txt:{
padding:5,
fontSize:18,
fontFamily: 'PacificoRegular',
}
答案 2 :(得分:0)
useEffect(()=>{
async function loadFonts(){
await Font.loadAsync({
'Montserrat': require("./assets/fonts/Montserrat/Montserrat-Regular.ttf"),
'Montserrat-SemiBold': require('./assets/fonts/Montserrat/Montserrat-SemiBold.ttf'),
'Montserrat-Bold': require('./assets/fonts/Montserrat/Montserrat-Bold.ttf'),
'Fascinate': require('./assets/fonts/Fascinate/Fascinate-Regular.ttf')
}).then(res=>{
console.log("FONTS LOADED!");
setLoaded(true)
}).catch(Err=>{
setLoaded(true);
console.log(Err);
});
}
loadFonts();
},[])
在你的 App.js 文件中使用这个 useEffect 加载,一旦加载,字体就可以在你的 expo 或 react-native 项目中的任何地方使用
const Heading = (color) => {
return({fontSize:45*fontScale, fontFamily: "Montserrat-SemiBold", color, marginTop: -10, marginLeft: InitialMargin, letterSpacing: 4})
}
确保您没有使用样式 fontWeight,因为它会覆盖 fontStyle 并且不会将 fontFamily 应用于您的文本。
答案 3 :(得分:0)
Font.loadAsync 已经过时并且被证明存在不可预测的问题。现在世博会推出了新的解决方案here
所以现在正确的代码是:
import {useFonts} from 'expo-font';
import AppLoading from "expo-app-loading";
let [fontsLoaded] = useFonts({
'Lobster': require('./assets/fonts/Lobster-Regular.ttf'),
});
if (!fontsLoaded) {
return <AppLoading/>;
}
...