在React Native Expo项目中设置默认字体族。

7
我正在尝试在RN Expo项目中设置默认字体(Lato-Regular)。我使用setCustomText来实现这一目标。https://github.com/Ajackster/react-native-global-props。这种方法在非Expo项目中运行得很好,但是现在我将我的项目移植到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 可能出现了什么问题?
1个回答

3

在此,您不需要等待字体加载完成就立即调用setState,您必须等待Font.loadAsync Promise被解析。

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();
}

2
不用谢,我之前也不知道react-native-global-props,我也学到了 :) - Freez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接