代码之家  ›  专栏  ›  技术社区  ›  tom harrison

将SVG作为react组件导入

  •  3
  • tom harrison  · 技术社区  · 7 年前

    我正在将svg作为组件导入react,但它 Style 如果我在 style 标记它加载svg,但显然缺少额外的样式

    我希望避免将所有样式移动到单独的样式中。css文件如果可能,如何在React中将svg作为组件导入,但保留所有样式?

    import React from 'react'
    
    export const StoffFarbe = () =>
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
         viewBox="0 0 40 40">
       <style type="text/css">
        .st0{fill:none;stroke:#1D1D1B;stroke-width:3.2003;stroke-linejoin:round;stroke-miterlimit:10;}
        .st1{fill:none;stroke:#1D1D1B;stroke-width:1.6001;stroke-linejoin:round;stroke-miterlimit:10;}
    </style>
    <g>
        <path className="st0" d="M6.3,33c-1.4-1.4-2.4-3.8,0.2-6.4s7.4-4.8,7.4-4.8s0.8-3.8,0.2-6.6c1.6-1.6,10.8-10.8,10.8-10.8l10.2,10.2
            c0,0-9.2,9.2-10.8,10.8c-3.2-1.4-6.2,0-6.2,0s-2.8,5-5,7.4C10.5,35,7.7,34.5,6.3,33z"/>
    </g>
    <line className="st1" x1="15.7" y1="13.8" x2="25.5" y2="23.6"/>
    <circle className="st1" cx="9.3" cy="29.8" r="0.4"/>
    <path className="st1" d="M20.1,9.4c0,0-0.4,1.4,1.6,2.2s3.4-1.2,4,0.6s-1.6,4.2,1.4,5.2c3,0.8,3.8-0.8,4.2,0.4"/>
    </svg>
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   KyleMit Steven Vachon    4 年前

    如果您使用create react app 2.0,现在可以这样做:

    import { ReactComponent as YourSvg } from './your-svg.svg';
    
    <div>
       <YourSvg />
    </div>
    
        2
  •  1
  •   Jordi Castilla    7 年前

    您可以导入样式表:

    import './StoffFarbe.css';
    

    CSS文件内部:

    .StoffFarbe {
        // add styles
    }
    

    另一种选择是将svg用作图像:

    <img src="StoffFarbe.svg" class="yourCSSClass">
    

    资料来源: