首先React-native不能直接引入SVG图片,所以我们要借助两个库来实现,废话不多说,下面直接给出详细过程
1 . 安装react-native-svg(参考我的package.json文件)
2.下载你喜欢的SVG图片,可在阿里图标库慢慢挑选,然后放在一个文件夹里面,加粗的目的是因为后面要用这个文件夹的名字,一般用svgs吧
3.将svg处理成一个js文件,因为稍后要用到的react-native-svg-uri这个库虽然可以直接使用文件路径的方式引入,但是在安卓下有bug,具体自行百度,这个js文件也可以百度获得,使用node处理的,会将svg图片处理成key:value的键值对,比较简单,具体代码如下,这里取名叫做getSvg.js(看你喜欢取什么取什么)
//导入node的文件模块
var fs = require('fs');
var path = require('path');
//定义想要处理的svg文件夹路径
const svgDir = path.resolve(__dirname, './svgs');
// 读取单个文件
function readfile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(path.join(svgDir, filename), 'utf8', function(err, data) {
console.log(data.replace(/<\?xml.*?\?>|<\!--.*?-->|<!DOCTYPE.*?>/g, ''));
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));
});
});
}
// 在当前的目录下生成svgs.js
readSvgs().then(data => {
let svgFile = 'export default ' + JSON.stringify(Object.assign.apply(this, data));
fs.writeFile(path.resolve(__dirname, './svgs.js'), svgFile, function(err) {
if(err) throw new Error(err);
})
}).catch(err => {
throw new Error(err);
});
4.上面两步走完之后你的文件夹里面应该有这些东西,一个svg图片集合,一个处理svg的脚本文件
5.打开控制台运行getSvg.js脚本
node getSvg.js
运行完毕后的目录结构是这样的
6.去react-native-svg-uri的github下载源码地址在这儿,但是这个库年代久远了,好多东西已经过期了,而且不能和最新版react-native-svg配合了,好在这个库非常简单且不依赖于其他库,所以我们下载他的源码自己改造一下
观察可知,这个库的核心就是这两个文件,首先针对index.js文件进行改造,改造就是删除了构造器函数,将state简写了,修改过期的生命周期函数的名字,还有就是导入utils时我改了个名字,改成了svgUriUtils下面就是修改后的代码
import React, {Component} from 'react';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import xmldom from 'xmldom';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import Svg, {
Circle,
Ellipse,
G,
LinearGradient,
RadialGradient,
Line,
Path,
Polygon,
Polyline,
Rect,
Text,
TSpan,
Defs,
Stop,
} from 'react-native-svg';
import * as utils from './svgUriUtils';
const ACCEPTED_SVG_ELEMENTS = [
'svg',
'g',
'circle',
'path',
'rect',
'defs',
'line',
'linearGradient',
'radialGradient',
'stop',
'ellipse',
'polygon',
'polyline',
'text',
'tspan',
];
// Attributes from SVG elements that are mapped directly.
const SVG_ATTS = ['viewBox', 'width', 'height'];
const G_ATTS = ['id'];
const CIRCLE_ATTS = ['cx', 'cy', 'r'];
const PATH_ATTS = ['d'];
const RECT_ATTS = ['width', 'height'];
const LINE_ATTS = ['x1', 'y1', 'x2', 'y2'];
const LINEARG_ATTS = LINE_ATTS.concat(['id', 'gradientUnits']);
const RADIALG_ATTS = CIRCLE_ATTS.concat(['id', 'gradientUnits']);
const STOP_ATTS = ['offset'];
const ELLIPSE_ATTS = ['cx', 'cy', 'rx', 'ry'];
const TEXT_ATTS = ['fontFamily', 'fontSize', 'fontWeight', 'textAnchor'];
const POLYGON_ATTS = ['points'];
const POLYLINE_ATTS = ['points'];
const COMMON_ATTS = [
'fill',
'fillOpacity',
'stroke',
'strokeWidth',
'strokeOpacity',
'opacity',
'strokeLinecap',
'strokeLinejoin',
'strokeDasharray',
'strokeDashoffset',
'x',
'y',
'rotate',
'scale',
'origin',
'originX',
'originY',
'transform',
'clipPath',
];
let ind = 0;
function fixYPosition(y, node) {
if (node.attributes) {
const fontSizeAttr = Object.keys(node.attributes).find(
(a) => node.attributes[a].name === 'font-size',
);
if (fontSizeAttr) {
return (
'' + (parseFloat(y) - parseFloat(node.attributes[fontSizeAttr].value))
);
}
}
if (!node.parentNode) {
return y;
}
return fixYPosition(y, node.parentNode);
}
class SvgUri extends Component {
state = {
fill: this.props.fill,
svgXmlData: this.props.svgXmlData,
createSVGElement: this.createSVGElement.bind(this),
obtainComponentAtts: this.obtainComponentAtts.bind(this),
inspectNode: this.inspectNode.bind(this),
fetchSVGData: this.fetchSVGData.bind(this),
isComponentMounted: false,
// Gets the image data from an URL or a static file
};
componentDidMount() {
if (this.props.source) {
console.log(this.props);
const source = resolveAssetSource(this.props.source) || {};
this.fetchSVGData(source.uri);
}
this.setState({
isComponentMounted: true,
});
// this.isComponentMounted = true;
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.source) {
const source = resolveAssetSource(nextProps.source) || {};
const oldSource = resolveAssetSource(this.props.source) || {};
if (source.uri !== oldSource.uri) {
this.fetchSVGData(source.uri);
}
}
if (nextProps.svgXmlData !== this.props.svgXmlData) {
this.setState({svgXmlData: nextProps.svgXmlData});
}
if (nextProps.fill !== this.props.fill) {
this.setState({fill: nextProps.fill});
}
}
componentWillUnmount() {
this.isComponentMounted = false;
}
async fetchSVGData(uri) {
let responseXML = null,
error = null;
try {
const response = await fetch(uri);
responseXML = await response.text();
} catch (e) {
error = e;
console.error('ERROR SVG', e);
} finally {
if (this.isComponentMounted) {
this.setState({svgXmlData: responseXML}, () => {
const {onLoad} = this.props;
if (onLoad && !error) {
onLoad();
}
});
}
}
return responseXML;
}
// Remove empty strings from children array
trimElementChilden(children) {
for (child of children) {
if (typeof child === 'string') {
if (child.trim().length === 0)
children.splice(children.indexOf(child), 1);
}
}
}
createSVGElement(node, childs) {
this.trimElementChilden(childs);
let componentAtts = {};
const i = ind++;
switch (node.nodeName) {
case 'svg':
componentAtts = this.obtainComponentAtts(node, SVG_ATTS);
if (this.props.width) {
componentAtts.width = this.props.width;
}
if (this.props.height) {
componentAtts.height = this.props.height;
}
return (
<Svg key={i} {...componentAtts}>
{childs}
</Svg>
);
case 'g':
componentAtts = this.obtainComponentAtts(node, G_ATTS);
return (
<G key={i} {...componentAtts}>
{childs}
</G>
);
case 'path':
componentAtts = this.obtainComponentAtts(node, PATH_ATTS);
return (
<Path key={i} {...componentAtts}>
{childs}
</Path>
);
case 'circle':
componentAtts = this.obtainComponentAtts(node, CIRCLE_ATTS);
return (
<Circle key={i} {...componentAtts}>
{childs}
</Circle>
);
case 'rect':
componentAtts = this.obtainComponentAtts(node, RECT_ATTS);
return (
<Rect key={i} {...componentAtts}>
{childs}
</Rect>
);
case 'line':
componentAtts = this.obtainComponentAtts(node, LINE_ATTS);
return (
<Line key={i} {...componentAtts}>
{childs}
</Line>
);
case 'defs':
return <Defs key={i}>{childs}</Defs>;
case 'linearGradient':
componentAtts = this.obtainComponentAtts(node, LINEARG_ATTS);
return (
<LinearGradient key={i} {...componentAtts}>
{childs}
</LinearGradient>
);
case 'radialGradient':
componentAtts = this.obtainComponentAtts(node, RADIALG_ATTS);
return (
<RadialGradient key={i} {...componentAtts}>
{childs}
</RadialGradient>
);
case 'stop':
componentAtts = this.obtainComponentAtts(node, STOP_ATTS);
return (
<Stop key={i} {...componentAtts}>
{childs}
</Stop>
);
case 'ellipse':
componentAtts = this.obtainComponentAtts(node, ELLIPSE_ATTS);
return (
<Ellipse key={i} {...componentAtts}>
{childs}
</Ellipse>
);
case 'polygon':
componentAtts = this.obtainComponentAtts(node, POLYGON_ATTS);
return (
<Polygon key={i} {...componentAtts}>
{childs}
</Polygon>
);
case 'polyline':
componentAtts = this.obtainComponentAtts(node, POLYLINE_ATTS);
return (
<Polyline key={i} {...componentAtts}>
{childs}
</Polyline>
);
case 'text':
componentAtts = this.obtainComponentAtts(node, TEXT_ATTS);
return (
<Text key={i} {...componentAtts}>
{childs}
</Text>
);
case 'tspan':
componentAtts = this.obtainComponentAtts(node, TEXT_ATTS);
if (componentAtts.y) {
componentAtts.y = fixYPosition(componentAtts.y, node);
}
return (
<TSpan key={i} {...componentAtts}>
{childs}
</TSpan>
);
default:
return null;
}
}
obtainComponentAtts({attributes}, enabledAttributes) {
const styleAtts = {};
if (this.state.fill && this.props.fillAll) {
styleAtts.fill = this.state.fill;
}
Array.from(attributes).forEach(({nodeName, nodeValue}) => {
Object.assign(
styleAtts,
utils.transformStyle({
nodeName,
nodeValue,
fillProp: this.state.fill,
}),
);
});
const componentAtts = Array.from(attributes)
.map(utils.camelCaseNodeName)
.map(utils.removePixelsFromNodeValue)
.filter(utils.getEnabledAttributes(enabledAttributes.concat(COMMON_ATTS)))
.reduce((acc, {nodeName, nodeValue}) => {
acc[nodeName] =
this.state.fill && nodeName === 'fill' && nodeValue !== 'none'
? this.state.fill
: nodeValue;
return acc;
}, {});
Object.assign(componentAtts, styleAtts);
return componentAtts;
}
inspectNode(node) {
// Only process accepted elements
if (!ACCEPTED_SVG_ELEMENTS.includes(node.nodeName)) {
return <View />;
}
// Process the xml node
const arrayElements = [];
// if have children process them.
// Recursive function.
if (node.childNodes && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
const isTextValue = node.childNodes[i].nodeValue;
if (isTextValue) {
arrayElements.push(node.childNodes[i].nodeValue);
} else {
const nodo = this.inspectNode(node.childNodes[i]);
if (nodo != null) {
arrayElements.push(nodo);
}
}
}
}
return this.createSVGElement(node, arrayElements);
}
render() {
try {
if (this.state.svgXmlData == null) {
return null;
}
const inputSVG = this.state.svgXmlData
.substring(
this.state.svgXmlData.indexOf('<svg '),
this.state.svgXmlData.indexOf('</svg>') + 6,
)
.replace(/<!-(.*?)->/g, '');
const doc = new xmldom.DOMParser().parseFromString(inputSVG);
const rootSVG = this.inspectNode(doc.childNodes[0]);
return <View style={this.props.style}>{rootSVG}</View>;
} catch (e) {
console.error('ERROR SVG', e);
return null;
}
}
}
SvgUri.propTypes = {
style: PropTypes.object,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
svgXmlData: PropTypes.string,
source: PropTypes.any,
fill: PropTypes.string,
onLoad: PropTypes.func,
fillAll: PropTypes.bool,
};
module.exports = SvgUri;
接下来直接复制utils过来就行了,如果直接复制我的全部代码,你可能要注意一下utils的导入路径和它的名字就行了
7.最后我们封装一个svg组件出来,这个百度可以找到,我这里是其中一份比较简单的,你可以自己定制,唯一要注意的就是两个导入的文件,第一个是刚才我们到github下载并改造的index文件,命名自己喜欢,第二个导入就是我们使用脚本生成的svg的js文件合集
/*
* @Description:svg组件
* @Autor: ZmSama
* @Date: 2020-10-02 11:09:58
*/
// Svg.js
import React, {Component} from 'react';
import SvgUri from '../utils/svgUri';
import svgs from '../assets/svgs';
export default class Svg extends Component {
render() {
const {color, size, style, icon} = this.props;
console.log(color);
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}
/>
);
}
}
8.最后在任意组件导入SVG并使用即可,这里要注意的地方就是,icon填入的字符串是我们用脚本生成的js中导出对象的key值(自己可以打开生成的脚本文件查看一下,建议先用vscode格式化一下,不然很乱看不出什么东西),其实就是svg的文件名字(这里我的是仓库管理),还有就是SVG是导入我们自己封装的不要导入react-native-svg的,切记。
效果
全部的过程就在这里了,希望能帮到要使用的朋友们