首页 > 解决方案 > 从对象渲染 SVG

问题描述

我有一个我正在处理的 React 项目,我试图从一组对象中渲染一个 SVG。但是,每当我尝试从 map 方法访问 SVG 时,都会出现错误。有没有更好的方法来完成我所缺少的过程。对于上下文:

locations: [
            { svg: SanFrancisco, city: "San Francisco, CA", number: 54 },
            { svg: Redwood, city: "Redwood City, CA", number: 1 },
            { svg: NewYork, city: " New York, NY", number: 17 },
            { svg: Portland, city: "Portland, OR", number: 10 }
           ]

SVG 已在此处作为 React 组件导入。

jsx中的用法:

{locations.map((location) => {
                            return (
                                <a href="#">
                                    {" "}
                                    <div className="locations-card card">
                                        {location.svg}
                                        <h2>{location.city}</h2>
                                        <p>{location.number} openings</p>
                                    </div>
                                </a>
                            );
                        })}

将location.svg记录到控制台会返回这种性质的对象

是否可以通过对象访问 svg 图标本身?

编辑:根据建议,下面的代码起到了作用

{locations.map((location) => {
                            return (
                                <a href="#">
                                    {" "}
                                    <div className="locations-card card">
                                        <location.svg/>
                                        <h2>{location.city}</h2>
                                        <p>{location.number} openings</p>
                                    </div>
                                </a>
                            );
                        })}

标签: javascriptarraysreactjsobjectsvg

解决方案


如果 svg 属性是react component

{locations.map((location) => {
    const Svg = location.svg; // --> get the component
    return (
      <a href="#">
         {" "}
       <div className="locations-card card">
           <Svg />{/* --> render it*/}
           <h2>{location.city}</h2>
           <p>{location.number} openings</p>
       </div>
      </a>
   );})}

推荐阅读