react-native 使用 阿里 iconfont字体图标

1,056 阅读1分钟
  1. 在 iconfont 官网,选择自己喜欢的字体图标,加入到自己的项目,下载下来,解压缩之后的目录是下面这样的

  1. 在项目根目录下 新建 assets/fonts 将 解压之后的文件,拷贝到该目录(其实只需要 iconfont.ttf 文件,但是因为后期会更改字体图标,所以就全部拷贝过去了)

  1. 打开package.json文件,配置字体路径

    "rnpm": {
        "assets": [
          "./assets/fonts/"
        ]
      }
    
  2. 执行以下命令,执行完成后,重新编译 rn项目

    react-native link
    npx react-native run-android
    
  3. 重启编辑器后会发现该字体文件已经自动拷贝到 android/app/src/main/assets/fonts目录 和配置到Info.plist文件中

至此,已经配置完成了

  1. 使用

    • 打开 demo_index.html 文件

  • 这里用到的是后4位字母为标记,引用时使用{'\u'+后4位字母},通过style中的fontSize来调整大小

  • 我自己使用的代码

    
    import React,{Component} from 'react';
    import {
      StyleSheet,
      View,
      Text
    } from 'react-native';
    export default class App extends Component {
      constructor() {
        super()
      }
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.iconStyle}>{'\ue600'}</Text>
            <Text style={styles.iconStyle}>{'\ue601'}</Text>
        </View>
        )
      }
    }
    const styles = StyleSheet.create({
      iconStyle: {
        fontFamily: 'iconfont',
        fontSize: 24,
        marginTop: 10,
        marginLeft: 10
      },
    })
    

注意:一定要为 文本添加上 fontFamily:'iconfont' 否则 字体图标是没办法显示出来的

为什么 fontFamily 一定要为 iconfont

打开 assets/fonts/iconfont.css

font-familly的属性值,需要和 该文件中的属性值保持一致