React-Nativeで @Font-Faceの動作を簡単にエミュレートします。
Reactネイティブでカスタムフォントを使用すると、さまざまなフォントの重みやスタイルを使用しようとすると複雑になります。 React Native TextStyleタイプには、 fontFamily 、 fontWeightおよびfontStyleのプロパティが含まれていますが、これらのプロパティはデフォルトの組み込みフォントに対してのみ機能し、カスタムフォントを使用する場合のサポートは限られています。このため、特定のフォントの重みとスタイルの選択は、目的のロードされたフォントファイルの正確な追記名を指定することにより、伝統的に実現されます。
例えば:
const style : ViewStyle = {
fontFamily : 'Roboto-MediumItalic' ,
} ;これにより、マージされたスタイルやテキストスタイルの構成を実現することが困難になります。好ましいソリューションは次のようなものかもしれません:
const style : ViewStyle = {
fontFamily : 'Roboto' ,
fontWeight : '500' ,
fontStyle : 'italic' ,
} ;このライブラリは、Reactネイティブ開発者がiOS、Android、およびWebのカスタムフォントを使用してfontWeightとfontStyleを使用できるようにすることにより、ライフを楽にすることを目的としています。
必要な依存関係をアプリケーションのpackage.jsonに追加します:
yarn add react-native-font-facesExpoを使用しており、追加のカスタムフォントファイルをアプリにロードする必要がある場合は、以下も追加します。
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() (React-native-dynamic-fonts)への呼び出しを追加して、リモートフォントを動的にロードします。 バージョン3.xでは、 FontFacesProvider簡素化し、 useFontFacesを削除しました。次の手順に従って移行します。
useFontFaces()のすべてのインスタンスを削除します。<FontFacesProvider/>を更新して、 onLoadingおよびonErrorプロップ(オプション)を提供します。 バージョン2.xでは、 FontFacesProviderとuseFontFacesを導入し、 enableFontFacesを削除しました。次の手順に従って移行します。
enableFontFaces()のすべてのインスタンスを削除します。<FontFacesProvider/>を追加します。const [fontsLoaded] = useFontFaces(...)内側の関数コンポーネントのボディ内に追加し、 fontsLoaded値を適切に処理します。