首页 > 解决方案 > 如何在 React Native 中显示 SVG 数据?

问题描述

我有一些 SVG 图像数据想导入到我的 React Native 应用程序中。

有什么方法可以获取我的原始 SVG 图像数据并显示它而不将其保存到文件中?

我有一个 api,它将根据任何给定的文本(coolProgrammer123)创建一个图像,并将返回 SVG 图像数据。

https://api.kwelo.com/v1/media/identicon/coolProgrammer123?format=base64

有任何想法吗?谢谢。

标签: react-nativesvg

解决方案


我建议你试试react-native-svg-uri

import SvgUri from 'react-native-svg-uri';

const TestSvgUri = () => (
  <View style={styles.container}>
    <SvgUri
      width="200"
      height="200"
      source={{uri:'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg'}}
    />
  </View>
);

更新

这是一个代码片段,介绍了如何使用axios从 URL 获取 SVG 并将其传递给Image标签,而无需使用上述npm包。

import React, { Component } from 'react';
import { View, Image } from 'react-native';
import axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageUri: ''
    }
  }

  componentDidMount() {
    this.getSvg();
  }

  getSvg = () => {
    let image_base64;
    axios.get('https://api.kwelo.com/v1/media/identicon/coolProgrammer123?format=base64')
      .then(response => {
        image_base64 = response.data;
        this.setState({
          ...this.state,
          imageUri: image_base64
        })
      })
      .catch(function (error) {
        console.log(error);
      });
      return image_base64;
  }

render(){
  return (
    <View>
      <Image
        style={{
          width: 81,
          height: 81,
          resizeMode: 'contain',
          marginTop: 180,
          marginLeft: 20,
          marginRight: 20,
          alignSelf: "center"
        }}
        source={{ uri: this.state.imageUri }}
/>
    </View>
  );
}
};



export default App;


推荐阅读