在 react native expo 中使用 iconfont 自定義圖示
阿新 • • 發佈:2020-10-22
1. 下載 iconfont 檔案
把在 https://www.iconfont.cn/ 上下載好的圖示解壓
2. 用 node.js 生成 iconfont.json 對映
在解壓好的資料夾裡增加一個新檔案 genJson.js
在 genJson.js
中寫入以下內容
const fs = require('fs') const path = require('path') const lineReader = require('readline').createInterface({ input: require('fs').createReadStream(path.join(__dirname, './iconfont.svg')), }) const names = [] console.log('create...') lineReader.on('line', function (line) { let words = line.split(' ') if (words[4] === '<glyph') { let [key, value] = [words[5].slice(12, -1), words[6].slice(11, -2)] if (value) { names.push(' "' + key + '":' + value) } } }) lineReader.on('close', function () { return fs.writeFile( path.resolve(__dirname, './iconfont.json'), '{\n' + names.join(',\n') + '\n}', function (err) { if (err) { throw new Error(err) } else { console.log('create successe.') } } ) })
執行命令 node genJson.js
生成 iconfont.json
生成後的 iconfont.json
檔案內容如下格式:
3. 配置 自定義圖示
在 components
資料夾下新建資料夾 iconfont
, 複製 步驟1 中 iconfont.ttf 和 步驟2 中的 iconfont.json, 並新建 index.ts
在 index.ts
中寫入以下內容:
import { createIconSet } from '@expo/vector-icons'; import glyphMap from './iconfont.json'; export default createIconSet(glyphMap, "iconfont", require('./iconfont.ttf'));
4. 使用方法
import Icon from '../components/iconfont'; export default function TabHot() { return ( <View style={styles.container}> <Text style={styles.title}>Tab Hot</Text> <Icon name="fire" size={26} style={{ marginBottom: -3 }} color="red" /> </View> ); }
圖示name的名字,開啟步驟1中下載的 demo_index.html 檢視