Load customised font in react native

落爺英雄遲暮 提交于 2021-01-29 11:22:57

问题


I want to load custom font i my app.

I try this

  • Create a assets/fonts where you can find the fonts i want to use
  • I add rnmp in the package.json like that : "rnmp": { "assets": ["./assets/fonts/"] }
  • I link like that: react-native link
  • Then i use my font like that : fontFamily: "Lato-Light",

    {
    
     "main": "node_modules/expo/AppEntry.js",
     "scripts": {
         "start": "expo start",
         "android": "expo start --android",
         "ios": "expo start --ios",
         "eject": "expo eject"
      },
     "dependencies": {
         "expo": "^32.0.6",
         "react": "16.5.0",
         "react-native": "https://github.com/expo/react-native/archive/sdk- 
     32.0.0.tar.gz",
     "react-navigation": "^3.11.0"
     },
    "devDependencies": {
         "babel-preset-expo": "^5.0.0"
    },
    "rnmp": {
         "assets": ["./assets/fonts/"]
    },
    "private": true
    }
    

The font should be load but i get this error :

"fontFamily" "Lato-Light" is not a system font and has not been loaded through Font.loadAsync


回答1:


I assume you are using expo in this project. As the error you've shown says, you just have to load the desired fonts in the app loading process. In you App.js file, import the fonts you want to use as const, and add an async call to load them into the app. You can use the following code:

//In  the import section
import {Font} from 'expo';
const Light = require('./assets/fonts/Lato-Light.ttf');

//In the componentDidMount
await Font.loadAsync({
    'Lato-Light': Light
}); 

Note the await in the Font.loadAsync call. You have to make the componentDidMount method async (async componentDidMount() {...}) and then add await before the Font... call.

Hope this helps!



来源:https://stackoverflow.com/questions/56558915/load-customised-font-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!