且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将SVG嵌入到ReactJS中

更新时间:2023-02-12 21:59:02

更新2016-05-27

As在React v15中,在React中对SVG的支持是(接近?)与当前浏览器对SVG的支持100%奇偶校验( source )。你只需要应用一些语法转换来使它与JSX兼容,就像你必须为HTML做的那样 class className style =color:purple style = {{color:'purple'}} )。对于任何命名空间(冒号分隔)属性,例如 xlink:href ,删除并将属性的第二部分大写,例如 xlinkHref 。以下是带有< defs> < use> 和内联样式的svg的示例:

As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (classclassName, style="color: purple"style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}

工作代码笔演示

有关特定支持的更多详细信息,请查看文档'支持的SVG属性列表。这里是(现已关闭) GitHub问题,它跟踪对命名空间SVG属性的支持。

For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.

上一个答案

你可以做一个简单的SVG嵌入,而不必通过剥离命名空间属性来使用 dangerouslySetInnerHTML 。例如,这有效:

You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

        render: function() {
            return (
                <svg viewBox="0 0 120 120">
                    <circle cx="60" cy="60" r="50"/>
                </svg>
            );
        }

此时你可以考虑添加像这样的道具填写,或其他任何可能有用的配置。

At which point you can think about adding props like fill, or whatever else might be useful to configure.