React Native中如何使用react-native-svg加载本地svg矢量图片?

1.下载react-native-svg库

npm:
npm install react-native-svg

yarn:
yarn add react-native-svg

2. 下载安装react-native-svg-transformer库 (必须安装)

React Native SVG transformer allows you to import SVG files in your React Native project the same way that you would in a Web application when using a library like SVGR to transform your imported SVG images into React components.This makes it possible to use the same code for React Native and Web.

npm:
npm install --dev react-native-svg-transformer

yarn:
yarn add --dev react-native-svg-transformer

3. 打包文件配置

文 件  名: metro.config.js
文件位置: 与package,json同级目录
版本要求: React Native v0.59 或者更高版本

将以下内容复制到metro.config.js文件中:

const { getDefaultConfig } = require("expo/metro-config");

module.exports = (() => {
  const config = getDefaultConfig(__dirname);

  const { transformer, resolver } = config;

  config.transformer = {
    ...transformer,
    babelTransformerPath: require.resolve("react-native-svg-transformer"),
  };
  config.resolver = {
    ...resolver,
    assetExts: resolver.assetExts.filter((ext) => ext !== "svg"),
    sourceExts: [...resolver.sourceExts, "svg"],
  };

  return config;
})();

4. 导入本地SVG矢量图片

import SvgImageFile from "./loading.svg";

5. 使用SVG的图片组件

/* Copyright (C) 2022 MasterCo. All Rights Reserved */

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
} from 'react-native';
import SvgImageFile  from "./loading.svg";

/*
 * SVG资源调试页面
 * @auther MasterCo
 * @since 2022-10-23
 */
export default class SvgTest extends Component {
    render() {
        return (
            <View style={styles.container}>
                <SvgImageFile  style={styles.loadingImage}/>
                <Text style={styles.hello}>Hello, World</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems:"center"
    },
    loadingImage :{
        width:100,
        height:100
    },
    hello: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10
    }
});

矢量图片可前往IconFont下载 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值