简体   繁体   English

React 中的条件 svg 渲染

[英]Conditional svg rendering in React

I'm working in React and have an object that looks something like this:我在 React 中工作并且有一个看起来像这样的 object:

[{ 
"title": "instagram", 
"href": "http://instagram.com"
"class": "instagram"
},
{ 
"title": "facebook", 
"href": "http://facebook.com"
"class": "facebook"
},
{ 
"title": "twitter", 
"href": "http://twitter.com",
"class": "twitter"
},
{ 
"title": "twitch", 
"href": "http://twitch.com"
"class": "twitch"
}]

and some variables that have an svg path like this...以及一些具有像这样的 svg 路径的变量......

const facebook = <svg path goes here>
const instagram = <svg path goes here>

and so on.等等。 My idea was to iterate through the object with the map method, and since the name of the classes is the same of the variables, that the variables content replaced the path and the icon showed, something like this:我的想法是使用 map 方法遍历 object,并且由于类的名称与变量相同,因此变量内容替换了路径并显示了图标,如下所示:

 <div>
            {array.map((item, i) =>{
        
                return <div>
                    <svg  width='40' height='40' viewBox="0 0 38.89 38.91"><path class="cls-1" d={item.class} transform="translate(-24 92.04)"/></svg>
                    </div>
            })
            }
        </div>

but the icons aren't showing up.但图标没有出现。 Why isn't the svg appearing?为什么没有出现 svg? What would be a better solution?什么是更好的解决方案?

The d attribute defines a path to be drawn. d属性定义要绘制的路径。

In your example, you are just assigning a string like "instagram" to the path's d attribute and expecting it to draw the instagram icon.在您的示例中,您只是将“instagram”之类的字符串分配给路径的d属性并期望它绘制 instagram 图标。

This won't work because d="instagram" is not a valid svg path command.这不起作用,因为d="instagram"不是有效的 svg 路径命令。

If you can edit your data source, why not just add the path there - under the path key in each item in the array?如果您可以编辑数据源,为什么不直接在其中添加路径 - 在数组中每个项目的路径键下?

[
    { 
        "title": "instagram", 
        "href": "http://instagram.com"
        "class": "instagram",
        "path": "<svg path goes here>"
    },
    ...
]

<div>
    {array.map((item, i) => {
        return (<div>
            <svg  width='40' height='40' viewBox="0 0 38.89 38.91">
                <path class="cls-1" d={ item.path } transform="translate(-24 92.04)"/>
            </svg>
        </div>)
    })}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM