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值。