我正在使用React Native和Expo,除了这个自定义字体的问题之外,一切都进行得很好。我将我的字体Lobster-Regular.ttf
放在./assets/fonts中,并且我一直在尝试加载它,如官方文档中所示:
componentDidMount() {
Font.loadAsync({
'Lobster': require('./assets/fonts/Lobster-Regular.ttf'),
});
}
然后,我将我的页眉样式设置为:
headerText: {
color: 'white',
fontSize: 30,
fontFamily: 'Lobster'
},
我得到的只是
fontFamily 'Lobster‘不是系统字体,未通过Font.loadAsync加载。
我是不是遗漏了什么?
发布于 2018-10-22 22:14:56
是。您没有注意到调用是Font.loadAsync()
。这意味着它加载asynchronously.比如:这需要一段时间。在加载字体之前,您无法呈现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 (
...
)
}
发布于 2020-05-08 17:37:12
安装 expo-font 包,因为有时expo -font版本与您的expo版本不兼容,因此,
第1步:
expo install expo-font
第2步:
class App extends React.Component {
state = {
fontLoaded: false,
};
componentDidMount() {
this.loadAssetsAsync();
}
async loadAssetsAsync() {
await Font.loadAsync({
// Load a font `Montserrat` from a static resource
MuseoSans500: require("./assets/fonts/museosans_500-webfont.ttf"),
MuseoSans700: require("./assets/fonts/museosans_700-webfont.ttf"),
});
this.setState({ fontLoaded: true });
}
render() {
if (!this.state.fontLoaded) {
return null; // render some progress indicator
}
return <AnyComponent />;
}
}
发布于 2020-01-29 07:19:27
**无状态函数中的react-native字体**
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
// fetchFonts from local files type ttf
const fetchFonts = () => {
return Font.loadAsync({
'PacificoRegular': require('../assets/Pacifico/Pacifico-Regular.ttf'),
});
};
*step3:使用状态*
// state font fetch control
const [fontloaded,setfontloaded]=useState(false);
**step4:使用加载的app **
if(!fontloaded){
return(
<AppLoading
startAsync={fetchFonts}
onFinish={()=>{setfontloaded(true)}}
onError={console.warn}/>
)
}
txt:{
padding:5,
fontSize:18,
fontFamily: 'PacificoRegular',
}
https://stackoverflow.com/questions/52917558
复制相似问题