2017-10-22 11 views
0

RN Expoプロジェクトで既定のフォント(Lato-Regular)を設定しようとしています。React Native Expoプロジェクトの既定のフォントファミリを設定します

私はこれを達成するためにsetCustomTextを使用しています。

このアプローチは、魅力のような非エクスポプロジェクトで実行していましたが、今は私のプロジェクトをExpoに移していて、アプリのデフォルトフォントに問題があるようです。

import React, { Component } from 'react' 
import { Styles } from 'react-native' 
import { Root } from './src/config/router' 
import { 
    setCustomText 
} from 'react-native-global-props' 

import { Font } from 'expo' 

class App extends Component { 
    constructor() { 
    super() 
    this.state = { 
     currentTab: null, 
     fontLoaded: false 
    } 
    } 

    getCurrentRouteName(navigationState) { 
    if (!navigationState) { 
     return null; 
    } 
    const route = navigationState.routes[navigationState.index] 
    if (route.routes) { 
     return this.getCurrentRouteName(route) 
    } 
    return route.routeName; 
    } 

    componentDidMount() { 
    Font.loadAsync({ 
     'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf') 
    }); 
    this.setState({ 
     fontLoaded: true 
    }, 
    () => this.defaultFonts()); 

} 

    defaultFonts(){ 
    const customTextProps = { 
     style: { 
     fontFamily: 'Lato-Regular' 
     } 
    } 
    setCustomText(customTextProps) 
    } 

    render() { 
    console.log(this); 
    return (
     this.state.fontLoaded ? 
     <Root 
     screenProps={{currentScreen: this.state.currentTab}} 
     /> : null 
) 
    } 
} 

export default App 

しかし、私はこのエラーを取得する:

enter image description here

あなたはフォントを要求した後、即座にsetStateを呼び出し、ロードされるフォントを待っていない問題がここ

答えて

1

かもしれないもの。あなたはFont.loadAsyncプロミスが解決するのを待たなければなりません。

componentDidMount() { 
    Font.loadAsync({ 
    'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf') 
    }) 
    .then(() => { 
     this.setState({ fontLoaded: true }); 
     this.defaultFonts(); 
    }); 
} 

async/await構文を使用することもできます。

async componentDidMount() { 
    await Font.loadAsync({ 
    'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf') 
    }) 
    this.setState({ fontLoaded: true }); 
    this.defaultFonts(); 
} 
+0

ありがとうございます、両方とも動作しています。使用されたasync/await。 – nikasv

+0

あなたは歓迎です、私は 'react-native-global-props'を知らなかった、何かを学んだこともあります:) – Freez

関連する問題