代码之家  ›  专栏  ›  技术社区  ›  Natesh bhat

如何将svg合并到React组件中?

  •  0
  • Natesh bhat  · 技术社区  · 7 年前

    以下是图标的svg:

    <?xml version="1.0"?>
    <svg viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg">
        <defs>
            <style>.cls-1{fill:#4d91bb;}.cls-2{fill:#2175aa;}.cls-3{fill:#c3edf5;}.cls-4{fill:#7ad0cb;}.cls-5{fill:#4dbab4;}</style>
        </defs>
        <title />
        <g data-name="23 Page Rank Badge" id="_23_Page_Rank_Badge">
            <path class="cls-1" d="M43.22,61,64,73,40,114.53,35.65,98.07l-16.43,4.46Zm41.57,0L64,73l24,41.57,4.35-16.46,16.43,4.46Z" />
            <polygon class="cls-2" points="39.48 67.43 39.48 81.48 55.02 81.48 57.59 84.06 64 72.97 43.22 60.97 39.48 67.43" />
            <polygon class="cls-2" points="92.52 74.36 84.78 60.97 64 72.97 71.87 86.6 76.98 81.48 92.52 81.48 92.52 74.36" />
            <rect class="cls-3" height="53.03" width="53.03" x="37.48" y="24.45" />
            <rect class="cls-3" height="53.03" transform="translate(54.78 -30.33) rotate(45)" width="53.03" x="37.48" y="24.45" />
            <circle class="cls-4" cx="64" cy="50.97" r="15" />
            <path class="cls-5" d="M52.74,51A15,15,0,0,1,65.87,36.09a15,15,0,1,0,0,29.74A15,15,0,0,1,52.74,51Z" />
        </g>
    </svg>
    

    const RankSVG = ({
        width = "53" ,
        height = "53"  , 
        viewBox="0 0 128 128"  ,
    
    }) => {
    
        return(
        <>
            <svg viewBox={viewBox} xmlns="http://www.w3.org/2000/svg">
                <style>{`.cls-1{fill:#4d91bb}.cls-2{fill:#2175aa}.cls-3{fill:#c3edf5}.cls-4{fill:#7ad0cb}.cls-5{fill:#4dbab4}`}</style>
            <path className="cls-1" d="M43.22,61,64,73,40,114.53,35.65,98.07l-16.43,4.46Zm41.57,0L64,73l24,41.57,4.35-16.46,16.43,4.46Z" /><polygon className="cls-2" points="39.48 67.43 39.48 81.48 55.02 81.48 57.59 84.06 64 72.97 43.22 60.97 39.48 67.43" /><polygon className="cls-2" points="92.52 74.36 84.78 60.97 64 72.97 71.87 86.6 76.98 81.48 92.52 81.48 92.52 74.36" /><rect className="cls-3" height={height} width={width} x="37.48" y="24.45" /><rect className="cls-3" height={height} transform="translate(54.78 -30.33) rotate(45)" width={width} x="37.48" y="24.45" /><circle className="cls-4" cx="64" cy="50.97" r="15" /><path className="cls-5" d="M52.74,51A15,15,0,0,1,65.87,36.09a15,15,0,1,0,0,29.74A15,15,0,0,1,52.74,51Z" /></svg>
        </>
        );
    }
    

    我做错了什么?如果我想在将来包含此类SVG,我应该记住哪些要点以避免犯错误?

    1 回复  |  直到 7 年前
        1
  •  1
  •   kev    7 年前

    您必须将您的样式移出到 .jsx .css 文件花括号 {} 单独的类会干扰.jsx {} 它们是用来表达的。

    以下是一个工作示例: https://codesandbox.io/s/718w386v46

    现在,或者,您可以将样式保留在.jsx文件中,但必须将它们定义为对象文字,并在用于表达式的花括号内添加一组花括号。