在React Native中加载自定义字体 [英] Load customised font in react native

查看:192
本文介绍了在React Native中加载自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中加载自定义字体.

I want to load custom font i my app.

我尝试

  • 创建资产/字体,在其中可以找到我要使用的字体
  • 我像这样在package.json中添加rnmp:"rnmp":{资产":["./assets/fonts/"]}
  • 我这样链接:react-native链接
  • 然后我像这样使用我的字体:fontFamily:"Lato-Light",

  • 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"不是系统字体,并且尚未通过Font.loadAsync加载

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

推荐答案

我假设您正在此项目中使用expo.正如您所显示的错误所言,您只需要在应用程序加载过程中加载所需的字体即可.在您的App.js文件中,导入要用作const的字体,并添加一个异步调用以将其加载到应用程序中.您可以使用以下代码:

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

请注意Font.loadAsync调用中的等待.您必须使componentDidMount方法异步(异步componentDidMount(){...}),然后在Font ...调用之前添加await.

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.

希望这会有所帮助!

这篇关于在React Native中加载自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆