React-native 中Svg字體圖標(biāo)的使用

1.需要引入的庫:

yarn add react-native-svg
react-native link react-native-svg
yarn add react-native-svg-uri

2.將所需要的svg圖片存入assets->SVG文件夾下,同級別建立腳本文件getSvg.js


SVG文件夾

腳本文件getSvg.js內(nèi)容:

//  getSvg.js
var fs = require('fs');
var path = require('path');
const svgDir = path.resolve(__dirname, './SVG');

// 讀取單個文件
function readfile(filename) {
return new Promise((resolve, reject) => {
  fs.readFile(path.join(svgDir, filename), 'utf8', function(err, data) {
    if (err) reject(err);
    resolve({
      [filename.slice(0, filename.lastIndexOf('.'))]: data,
    });
  });
});
}

// 讀取SVG文件夾下所有svg
function readSvgs() {
return new Promise((resolve, reject) => {
 fs.readdir(svgDir, function(err, files) {
   if (err) reject(err);
   Promise.all(files.map(filename => readfile(filename)))
    .then(data => resolve(data))
    .catch(err => reject(err));
 });
});
}

// 生成js文件
readSvgs().then(data => {
let svgFile = 'export default ' + JSON.stringify(Object.assign.apply(this, data));
svgFile = svgFile.replace(/\\n/g,'');
svgFile = svgFile.replace(/>[ ]+</g,"><");
fs.writeFile(path.resolve(__dirname, './Svg.js'), svgFile, function(err) {
  if(err) throw new Error(err);
})
}).catch(err => {
  throw new Error(err);

});

打開新的終端,進入項目的assets文件下,執(zhí)行node getSvg.js,生成Svg.js文件。
Svg.js文件結(jié)構(gòu)如下:

// svgs.js
export default {
  'svgName1': 'xmlData1...',
  'svgName2': 'xmlData2...',
  ...
}

3.同級別建立Svgs.js,封裝Svg Component

// Svgs.js
import React, { Component } from 'react';

import SvgUri from 'react-native-svg-uri';
import svgs from './Svg';

export default class Svgs extends Component<SvgProperties,void>{
  render() {
    const {
      icon,
      color,
      size,
      style
    } = this.props;
    let svgXmlData = svgs[icon];
    if (!svgXmlData) {
     let err_msg = `沒有"${icon}"這個icon,請下載最新的icomoo并 npm run build-js`;
     throw new Error(err_msg);
    }
    return (
      <SvgUri
        width={size}
        height={size}
        svgXmlData = {svgXmlData}
        fill={color}
        style={style}
      />
    )
  }
}

同級別,建立SingleSvg.js文件(用來實現(xiàn)一個svg圖片中出現(xiàn)多種顏色效果)

//SingleSvg.js
import React,{Component} from 'react';
import {Dimensions} from 'react-native';
import Svg,{Path,Circle,Text}from 'react-native-svg';
const { width, height } = Dimensions.get('window');
export default class SingleSvg extends Component{
render(){
    return(
        <Svg height={height * 0.5} width={width * 0.5} viewBox="0 0 80 80">
          <Path
            fill={this.props.pathColor} 
            class="cls-1" 
            d="M8.41,19.22H3.89a2.64,2.64,0,0,1-2.82-2.77V4.53a2.79,2.79,0,0,1,2.79-3H20.15a2.82,2.82,0,0,1,2,.89,2.72,2.72,0,0,1,.75,2V16.41a2.67,2.67,0,0,1-2.78,2.81H15.64L13,21.83a1.39,1.39,0,0,1-.95.4,1.34,1.34,0,0,1-.94-.39ZM3.86,2.66A1.68,1.68,0,0,0,2.17,4.49v12a1.56,1.56,0,0,0,.45,1.2,1.58,1.58,0,0,0,1.24.45h5l.16.16,2.86,2.78a.23.23,0,0,0,.17.07.25.25,0,0,0,.18-.08l3-2.93h5a1.56,1.56,0,0,0,1.19-.45,1.6,1.6,0,0,0,.45-1.23v-12a1.7,1.7,0,0,0-.45-1.27,1.68,1.68,0,0,0-1.23-.53Z"
          />
           <Circle
            fill={this.props.circleColor}  
            class="cls-2"
             cx="19.5" 
             cy="4.5" 
             r="4.5"
          >
          </Circle>   
        </Svg>
    )
}
}

若要實現(xiàn)特殊樣式,如圈中包含數(shù)字的效果,則只需要在<Svg><Circle>的同級別下面添加Test

<Svg height={height * 0.5} width={width * 0.5} viewBox="0 0 80 80">
          <Path
            fill={this.props.pathColor} 
            class="cls-1" 
            d="M8.41,19.22H3.89a2.64,2.64,0,0,1-2.82-2.77V4.53a2.79,2.79,0,0,1,2.79-3H20.15a2.82,2.82,0,0,1,2,.89,2.72,2.72,0,0,1,.75,2V16.41a2.67,2.67,0,0,1-2.78,2.81H15.64L13,21.83a1.39,1.39,0,0,1-.95.4,1.34,1.34,0,0,1-.94-.39ZM3.86,2.66A1.68,1.68,0,0,0,2.17,4.49v12a1.56,1.56,0,0,0,.45,1.2,1.58,1.58,0,0,0,1.24.45h5l.16.16,2.86,2.78a.23.23,0,0,0,.17.07.25.25,0,0,0,.18-.08l3-2.93h5a1.56,1.56,0,0,0,1.19-.45,1.6,1.6,0,0,0,.45-1.23v-12a1.7,1.7,0,0,0-.45-1.27,1.68,1.68,0,0,0-1.23-.53Z"
          />
           <Circle
            fill={this.props.circleColor}  
            class="cls-2"
             cx="19.5" 
             cy="4.5" 
             r="4.5"
          >
          </Circle>   
          <Text fill='#fff' x='16.5' y='6.0' fontSize='5'>12</Text>  
        </Svg>

4.運行時,引入Svgs.js和SingleSvg.js

//app.js
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
import Svgs from './assets/Svgs';
import SingleSvg from './assets/SingleSvg';


type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Svgs icon='icon-access' size='30' color='green'></Svgs>
        <Svgs icon='icons-pay' size='40' color='red'></Svgs>
        <Svgs icon='icons-reset' size='50' color='blue'></Svgs>
        <Svgs icon='icons-me-help' size='50' color='orange'></Svgs>
        <Svgs icon='icons-bang' size='40' color='blue'></Svgs>
        <Svgs icon='icons-tab-store-outline' size='50' color='red'></Svgs>
        <Svgs icon='icons-back' size='50'></Svgs>
    <Svgs icon='icons-weixin' size='50' ></Svgs>
        <Svgs icon='icons-time' size='50' color='red'></Svgs> 
        <Svgs icon='icons-selected' size='50' color='yellow'></Svgs>
        <Svgs icon='icons-write' size='50' color='yellow'></Svgs>
        <Svgs icon='icons-up' size='50' color='yellow'></Svgs>
        <Svgs icon='icons-share' size='50' color='red'></Svgs>
        <SingleSvg pathColor='#000000' circleColor='red'></SingleSvg>
       
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    paddingTop:300,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

5.運行結(jié)果
無數(shù)字


效果1

有數(shù)字


效果2

注:原svg圖片文件中必須含有fill屬性,否則默認黑色,且無法修改顏色。
具體參照簡書react-native icon解決方案(svg)

ps:github中項目demo

新增加svg后,node執(zhí)行完之后需要重新跑一遍。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 概要 64學(xué)時 3.5學(xué)分 章節(jié)安排 電子商務(wù)網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,851評論 0 3
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,817評論 1 45
  • 面試題一:https://github.com/jimuyouyou/node-interview-questio...
    R_X閱讀 1,761評論 0 5
  • ** 在開發(fā)app的過程中總是少不了各種各樣的icon圖標(biāo)。移動端和pc端的解決方式各有不同,而RN與之前的開發(fā)方...
    cloudZqy閱讀 29,672評論 34 33
  • 晚飯點,看著上兩頓的剩菜,還有中午未洗的鍋,打算剩菜就饅頭,配罐罐茶就搞定晚飯,我想起了三小姐,和三小姐的火鍋。 ...
    十四小姐閱讀 263評論 0 2

友情鏈接更多精彩內(nèi)容