reactjs – 如何在React中引用本地svg?

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在React中引用本地svg?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码编译得很好,但图标没有显示

Icon.jsx组件:

import React from 'react';
import { css } from 'emotion';

import ArrowRight from "./arrow-right.svg";

export const iconTypes = {
    arrowRight: 'ARROW_RIGHT',// arrowLeft: 'ARROW_LEFT',}

const iconSrc = {
    ARROW_RIGHT: ArrowRight,// ARROW_LEFT: ArrowLeft,}


export default function Icon({ type }) {
    return (
        <div>
            <img src={iconSrc[type]}/>
        </div>
    )
};

在浏览器中,请求如下所示:

http://localhost:9001/%22data:image/svg+xml,%3Csvg%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20width='512'%20height='512'%20viewBox='0%200%20512%20512'%3E%20%3Ctitle%3E%3C/title%3E%20%3Cg%20id='icomoon-ignore'%3E%20%3C/g%3E%20%3Cpath%20d='M310.627%20438.627l160-160c12.497-12.496%2012.497-32.758%200-45.255l-160-160c-12.497-12.496-32.758-12.496-45.255%200s-12.497%2032.758%200%2045.255l105.373%20105.373h-306.745c-17.673%200-32%2014.327-32%2032s14.327%2032%2032%2032h306.745l-105.373%20105.373c-6.248%206.248-9.372%2014.438-9.372%2022.627s3.124%2016.379%209.372%2022.627c12.497%2012.497%2032.758%2012.497%2045.255%200z'%3E%3C/path%3E%20%3C/svg%3E%22

Icon.jsx的故事:

import { action } from "@storybook/addon-actions"; 
import Icon from "../components/Icon/Index"; 
import { iconTypes } from "../components/Icon/Index";


    storiesOf("Icon",module)
        .add("with text",() => (
            <Icon type={iconTypes.arrowRight}>
            </Icon>
        ));

当我用一个http路径填充src(例如:“https://s.cdpn.io/3/kiwi.svg”)时,它工作得很好.

当我直接在浏览器中打开svg文件时,它也打开正常.

任何帮助,将不胜感激.

使用svg内联而不是图像要好得多.参数设置也更容易(例如尺寸):

Icon.jsx

import React from 'react';

export const iconTypes = {
  arrowRight: 'ARROW_RIGHT',arrowLeft: 'ARROW_LEFT',}

export default function Icon({ type = iconTypes.arrowRight,size = 512 }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox='0 0 512 512'>
      {type === iconTypes.arrowRight &&
        <path d='M310.627 438.627l160-160c12.497-12.496 12.497-32.758 0-45.255l-160-160c-12.497-12.496-32.758-12.496-45.255 0s-12.497 32.758 0 45.255l105.373 105.373h-306.745c-17.673 0-32 14.327-32 32s14.327 32 32 32h306.745l-105.373 105.373c-6.248 6.248-9.372 14.438-9.372 22.627s3.124 16.379 9.372 22.627c12.497 12.497 32.758 12.497 45.255 0z' />
      }
      {type === iconTypes.arrowLeft &&
        <path d="..." />
      }
    </svg>
  )
};

注意:您应该保留viewBox prop硬编码512以使比例正常工作.

猜你在找的React相关文章