react native font faces
v4.1.4
在反应本性中轻松模仿 @font-face行为。
在尝试使用不同的字体重量和样式工作时,在React Antial中使用自定义字体变得复杂。即使React本机TextStyle类型都包含了fontFamily , fontWeight和fontStyle的属性,但这些属性似乎仅适用于默认的内置字体,并且在使用自定义字体时的支持有限。因此,传统上选择特定的字体重量和样式是通过指定所需已加载字体文件的确切后录名称来实现的。
例如:
const style : ViewStyle = {
fontFamily : 'Roboto-MediumItalic' ,
} ;这使得很难获得合并的样式或文本样式组成。最好的解决方案可能是这样的:
const style : ViewStyle = {
fontFamily : 'Roboto' ,
fontWeight : '500' ,
fontStyle : 'italic' ,
} ;该图书馆旨在通过允许React React使用iOS,Android和Web上的自定义字体的fontWeight和fontStyle来使生活更轻松。
将所需的依赖项添加到您的应用程序package.json 。
yarn add react-native-font-faces如果您使用的是Expo,并且需要将其他自定义字体文件加载到您的应用中,请添加以下内容:
yarn add expo-font将呼叫添加到应用程序的输入点中的enableFontFaces() ,并导入所需的字体面。然后,请按照通常的期望使用字体家庭:
// App.tsx
import React from 'react' ;
import { useFonts } from 'expo-font' ;
import { AppLoading } from 'expo' ;
import { AppContent } from './AppContent' ;
import { Roboto_All , enableFontFaces , getExpoFontMap } from 'react-native-font-faces' ;
enableFontFaces ( Roboto_All ) ;
export default function App ( ) {
const [ loaded , error ] = useFonts ( getExpoFontMap ( Roboto_All ) ) ;
if ( ! loaded ) {
return < AppLoading /> ;
} else if ( error ) {
return < Text > { error . message } </ Text > ;
} else {
return (
< View style = { styles . container } >
< StatusBar style = "auto" />
< Text style = { styles . text } > This should be Regular </ Text >
< Text style = { [ styles . text , styles . italic ] } > This should be Italic </ Text >
< Text style = { [ styles . text , styles . bold ] } > This should be Bold </ Text >
< Text style = { [ styles . text , styles . bold , styles . italic ] } > This should be BoldItalic </ Text >
< Text style = { [ styles . text , styles . thin ] } > This should be Thin </ Text >
< Text style = { [ styles . text , styles . thin , styles . italic ] } > This should be ThinItalic </ Text >
</ View >
) ;
}
}
const styles = StyleSheet . create ( {
text : {
fontFamily : 'Roboto' ,
} ,
bold : {
fontWeight : 'bold' ,
} ,
thin : {
fontWeight : '100' ,
} ,
italic : {
fontStyle : 'italic' ,
} ,
container : {
flex : 1 ,
backgroundColor : '#fff' ,
alignItems : 'center' ,
justifyContent : 'center' ,
} ,
} ) ; 在版本4.x中,我们删除了FontFacesProvider并添加了enableFontFaces 。按照以下步骤迁移:
<FontFacesProvider /> 。enableFontFaces() 。useFonts() (expo-font)或loadFonts() (反应本机范围)中,以动态加载远程字体。 在版本3.x中,我们简化了FontFacesProvider和删除的useFontFaces 。按照以下步骤迁移:
useFontFaces()的实例。<FontFacesProvider/>以提供onLoading和onError Props(可选)。 在版本2.x中,我们介绍了FontFacesProvider和useFontFaces ,并删除了enableFontFaces 。按照以下步骤迁移:
enableFontFaces() 。<FontFacesProvider/> 。const [fontsLoaded] = useFontFaces(...) ,并适当处理fontsLoaded值。