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

时间:2018-12-23 10:19:34

标签: css reactjs web svg

以下是该图标的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 个答案:

答案 0 :(得分:1)

您必须将样式从.jsx文件移到.css文件中。分隔类的花括号{}干扰了用于表达式的.jsx {}

这是一个有效的示例: https://codesandbox.io/s/718w386v46

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