全局样式表中的Expo字体

时间:2017-02-13 18:10:17

标签: react-native exponentjs expo

我正在使用Expo,需要在我的全局样式表中使用自定义字体。世博会documents这个,但在我的情况下它是不相关的,因为componentDidMount()只在一个类中执行:

class App extends React.Component {
  componentDidMount() {
    Font.loadAsync({
      'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
    });
  }

  // ...
}

我的全局样式表如下所示:

const React = require('react-native');

import {
  Dimensions,
  StatusBar,
} from 'react-native';

const { StyleSheet } = React;

export default {
  // ...
}

3 个答案:

答案 0 :(得分:1)

Expo中的字体加载是“懒惰的”,因为您可以在加载之前创建引用字体的StyleSheet对象。例如,此代码有效:

async function exampleAsync() {
  let stylesheet = StyleSheet.create({
    fancyText: {
      ...Expo.Font.style('open-sans-bold'),
    },
  });

  await Expo.Font.loadAsync({
    'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
  });
}

因此,您无需在Expo.Font.loadAsync内拨打componentDidMount,并且可以在加载字体之前调用StyleSheet.createExpo.Font.style

重要的是,在渲染样式使用加载字体的组件之前,等待Expo.Font.loadAsync完成。

答案 1 :(得分:0)

我最后只是在导航文件中加载字体,然后能够在我的全局样式表和整个应用程序中访问这些字体。

答案 2 :(得分:0)

你可以做的只是在你的root / top组件中添加一个状态标志,检查字体异步是否已经完成。

然后在render方法中添加一个条件,以确保只有在成功加载字体后才会呈现子组件。请参阅示例

     export default class App extends React.Component {
      state = {
        fontLoaded: false,
      }

      componentDidMount() {
        this.loadAssetsAsync();
      }

      async loadAssetsAsync() {
        await Expo.Font.loadAsync({
         'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
        });;

        this.setState({ fontLoaded: true });
      }

      render() {
        if (!this.state.fontLoaded) {
          return <AppLoading />;  // render some progress indicator
        }

        return (
          <Navigator />    //render your child components tree
        );
      }
    }