代码之家  ›  专栏  ›  技术社区  ›  Phil Mok

React Native无法将自定义字体与Expo字体一起使用。loadAsync

  •  1
  • Phil Mok  · 技术社区  · 7 年前

    我正在尝试在我的应用程序中使用谷歌字体,并遵循了文档 here 没有运气。我下载了字体并使用了Expo推荐的文件结构。医生说要使用 async componentDidMount 你可以在下面的代码中看到我在做什么。我见过其他人成功地使用 async componentWillMount 但这对我不起作用。

    我收到的错误消息是:

    console.error: "fontFamily 'anton-regular' is not a system font and has not been loaded through Expo.Font.LoadAsync."

    我的控制台。日志,共页 fonts loaded: true 在我得到字体错误之前,在远程调试器中弹出。

    import React, { Component } from 'react';
    import { Font } from 'expo';
    import...
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = { fontLoaded: false };
      }
    
      async componentDidMount() {
        try {
          await Font.loadAsync({
            'anton-regular': require('./assets/fonts/Anton-Regular.ttf'),
          });
          this.setState({ fontLoaded: true });
          console.log('fonts are loaded');
        } catch (error) {
          console.log(error);
        }
      }
    
      render() {
        if (this.state.fontLoaded) {
          console.log('fonts loaded: ', this.state.fontLoaded)
          return (
            <Root>
              <Provider store={store}>
                <AppWithNavigationState />
              </Provider>
            </Root>
          );
        }
        return (
          <Root>
            <LoadingScreen />
          </Root>
        );
      }
    }
    

    编辑

    根据埃文·培根的建议,我将 Font.loadAsyc 尝试/捕获,但未捕获错误。我还将以下内容添加到我的应用程序中。json,无更改。

     "packagerOpts": {
       "assetExts": ["ttf"]
     },
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Phil Mok    7 年前

    终于弄明白了。原来我在使用字体的一个地方有一个尾随空格,如下所示:

    <Text style={{ fontFamily: 'anton-regular ' }}>I'm dumb.</Text>

    有趣的是,我可以从 app.json

    "packagerOpts": {
      "assetExts": ["ttf"]
    },
    

    字体仍然有效。