如何在React Native应用中使用新字体



我正在使用Create-React-Native-App。我不使用" Android Studio或其他任何东西",也使用Sublime Text Editor和Expo Mobile App仅在移动设备中查看输出。

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

预先感谢

博览会在其文档中很好地涵盖了这一点。当您使用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'),
    });
  }
  // ...
}

那是要点,几乎从博览会文档复制/粘贴

您可以像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 />
    );
  }
}
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>
    );
  }
}

最新更新