📜  react native import svg image - Javascript(1)

📅  最后修改于: 2023-12-03 15:34:38.597000             🧑  作者: Mango

React Native Import SVG Image

When it comes to displaying images in a React Native application, SVG images have become increasingly popular due to their scalability and high-quality appearance on all device sizes and resolutions. In this article, we will explore how to import and use SVG images in a React Native application.

Installation

First, we need to install the react-native-svg package by running the following command:

npm install --save react-native-svg

After installation, we need to link the package by running:

react-native link react-native-svg
Importing SVG images

To import an SVG image in a React Native application, we need to create an SvgUri component and pass the image source as the uri props. For example:

import React from 'react';
import { SvgUri } from 'react-native-svg';

const MyComponent = () => {
  const imageSource = { uri: 'https://example.com/myimage.svg' };
  return (
    <SvgUri
      width={200}
      height={200}
      uri={imageSource.uri}
    />
  );
};

export default MyComponent;

In the example above, we imported the SvgUri component from the react-native-svg library, created an imageSource object with the URI of the SVG image, and passed it as the uri prop to the SvgUri component.

We can also import SVG images from the local directory by using the require() function. For example:

import React from 'react';
import { SvgUri } from 'react-native-svg';
import MyImage from './images/myimage.svg';

const MyComponent = () => {
  return (
    <SvgUri
      width={200}
      height={200}
      uri={MyImage}
    />
  );
};

export default MyComponent;

In the example above, we imported the SVG image from the local directory and passed it as the uri prop to the SvgUri component.

SVG Styling

SVG images can be easily styled in a React Native application using the style prop. For example:

import React from 'react';
import { SvgUri } from 'react-native-svg';
import MyImage from './images/myimage.svg';

const MyComponent = () => {
  const imageStyle = { width: 200, height: 200, backgroundColor: 'red' };
  return (
    <SvgUri
      style={imageStyle}
      uri={MyImage}
    />
  );
};

export default MyComponent;

In the example above, we created an imageStyle object with custom width, height, and background color and passed it as the style prop to the SvgUri component.

Conclusion

In conclusion, importing SVG images in a React Native application is a simple process that can greatly enhance the appearance and scalability of your images. With the react-native-svg package, you can easily import, style, and display SVG images in your application.