【问题标题】:Loading a custom font on React Native Expo gives an error在 React Native Expo 上加载自定义字体会出错
【发布时间】:2019-10-12 22:19:37
【问题描述】:

所以我正在尝试使用 React Native Expo CLI 创建一个应用程序。我已经安装了空白版本。我正在尝试将 Open Sans 字体导入我的应用程序。到目前为止,我已经完成了以下步骤:

  1. 在我的“assets”文件夹中创建了一个名为“fonts”的文件夹,将 Open Sans 字体的 ttf 文件放入其中。

  2. 在我的App.js文件中添加了以下代码

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Font from 'expo-font';

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      fontLoaded: false
    };
  }
  async componentDidMount() {
    try {
      await Font.loadAsync({
        'OpenSans': require('./assets/fonts/OpenSans.ttf')
      });
      this.setState({ fontLoaded: true });
    }
    catch( error ) {
      console.log(error)
    }
  }
  render() {
    return(
      <View>
        <Text style={styles.text}>Test</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  text: {
    fontFamily: 'OpenSans',
  }
});

很遗憾,我遇到了一个错误,我在互联网上看到的所有解决方案都没有帮助我。我得到的错误如下:

fontFamily "OpenSans" is not a system font and has not been loaded through Font.loadAsync.

- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.

- If this is a custom font, be sure to load it with Font.loadAsync.
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
- ... 24 more stack frames from framework internals

【问题讨论】:

    标签: reactjs react-native expo


    【解决方案1】:

    您在安装应用程序后加载字体,这就是您出现该错误的原因。

    您的渲染方法应如下所示:

    render() {
        if (!this.state.fontLoaded) {
            return (<View>{/*some loader*/}</View>);
        }
        return(
          <View>
            <Text style={styles.text}>Test</Text>
          </View>
        );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多