简体   繁体   中英

How to use new font in react native app?

I am using create-react-native-app. I am not using 'android studio or anything', Also i am using sublime text editor and expo mobile app to see the output in mobile device only.

I want to import new font. i don't know flow what should add first.

thanks in advance,

Expo covers this in their docs pretty well. When you use create-react-native-app you're using expo, so follow their docs.

Even if you'd created your app using react-native init <MyAppName> you could still install their SDK...

npm install --save expo

Then just

import { Font } from 'expo';

Use this to load your font from the assets

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

  // ...
}

That's the gist, pretty much copy/paste from the Expo Docs

You can load the font once in your parent component like app.js for example:

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>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM