【问题标题】:How to use new font in react native app?如何在反应原生应用程序中使用新字体?
【发布时间】:2017-09-27 10:00:05
【问题描述】:

我正在使用 create-react-native-app。我没有使用“android studio 或任何东西”,我也使用 sublime 文本编辑器和 expo 移动应用程序来查看移动设备中的输出。

我想导入新字体。我不知道应该先添加什么。

提前致谢,

【问题讨论】:

标签: react-native fonts custom-font


【解决方案1】:

Expo 在他们的文档中很好地涵盖了这一点。当您使用 create-react-native-app 时,您使用的是 expo,因此请遵循他们的文档。

即使您使用 react-native init <MyAppName> 创建应用程序,您仍然可以安装他们的 SDK...

npm install --save expo

那么就

import { Font } from 'expo';

使用它从资产中加载您的字体

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

  // ...
}

这就是要点,几乎从Expo Docs复制/粘贴

【讨论】:

  • 我在周围使用通用组件..所以我在哪里导入这个 import { Font } from 'expo';
【解决方案2】:

您可以在父组件中加载一次字体,例如 app.js:

import React from 'react';
import { Font } from 'expo';
import Main from './src/components/Main';
import { Text } from 'react-native';


export default class App extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    amount: '',
    isReady: false
  };
  }

  componentDidMount() {
    this._loadFontsAsync();
  }

  _loadFontsAsync = async () => {
    await Font.loadAsync({ FONT_NAME: require('FONT_SOURCE')});
    this.setState({ isReady: true })
  }

  render() {
    if (!this.state.isReady) {
      return <Text>Loading</Text>
    }
    return (
      <Main />
    );
  }
}

【讨论】:

    【解决方案3】:
    export default class App extends React.Component {
      state = {
        fontLoaded: false,
      };
    
      async componentDidMount() {
        await Font.loadAsync({
          'helvetica': helveticaFont,
          'roboto-condensed-light': robotoCondensedLight,
          'roboto-condensed-regular': robotoCondensedRegular,
          'roboto-condensed-bold': robotoCondensedBold,
        });
        this.setState({ fontLoaded: true });
      }
    
      render() {
        return (
          <View >
            {
              this.state.fontLoaded ? (
                <SignIn></SignIn>
              ) : null
            }
          </View>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多