備忘録
関数コンポーネントでカスタムフォントを使っている記事が少なかったのでメモ
スマホで見るとこんな感じ
環境
使用プラットフォーム:ReactNative + Expo
使用フォント:Yomogi(assetsフォルダ内に入れています)
カスタムフォントの導入
App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { HomeScreen } from './src/Home';
export default function App() {
const Drawer = createDrawerNavigator();
return (
<NavigationContainer>
<StatusBar hidden />
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
DrawerNavigatorを使って初期状態にHomeScreenを表示しています。
HomeScreenの特定箇所のテキストにカスタムフォントを適用したいので、Home.jsで作業していきます。
home.js
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import * as Font from 'expo-font';
export const HomeScreen = () => {
const navigation = useNavigation();
const [fontLoaded, setFontLoaded] = useState(false);
useEffect(() => {
const subscription = navigation.addListener('focus', async () => {
await Font.loadAsync({
'Yomogi': require('../assets/Yomogi-Regular.ttf')
}).then(() => {
setFontLoaded(true);
})
});
return subscription;
}, []);
return (
<View style={styles.container}>
{fontLoaded &&
<Text style={styles.hello}>こんにちは</Text>
}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'pink',
alignItems: 'center',
justifyContent: 'center',
},
hello: {
fontSize: 70,
fontFamily: 'Yomogi',
}
});
カスタムフォントをロードするためにはexpo-font
のloadAsync
を使います。今回の場合は、HomeScreen
にfocus
した際にロードを行うようにしました。また、フォントがしっかりロードされてからテキストが描画される必要があるため、fontLoaded
がtrue
の時にテキストが表示されるようにしています。