从对象渲染 SVG

Chi*_*dex 3 javascript arrays svg object reactjs

我正在开发一个 React 项目,并且尝试从对象数组中渲染 SVG。然而,每当我尝试从地图方法访问 SVG 时,我都会收到错误。有没有更好的方法来完成我所缺少的过程。对于上下文:

\n
locations: [\n            { svg: SanFrancisco, city: "San Francisco, CA", number: 54 },\n            { svg: Redwood, city: "Redwood City, CA", number: 1 },\n            { svg: NewYork, city: " New York, NY", number: 17 },\n            { svg: Portland, city: "Portland, OR", number: 10 }\n           ]\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

jsx中的用法:

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

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

\n
    \n
  • {$$typeof: 符号(react.forward_ref), 渲染: \xc6\x92}$$typeof: 符号(react.forward_ref)渲染: \xc6\x92 SvgSanfrancisco({ title, titleId, ...props }, svgRef)显示名称:(...)获取显示名称:\xc6\x92 ()设置显示名称:\xc6\x92 (名称)参数:(...)调用者:(...)长度:1名称:“set”原型:{构造函数:\xc6\x92}原型:\xc6\x92 ()[[FunctionLocation]]:react.development.js:1401[[Scopes]]:Scopes[4]原型:Object...*
  • \n
\n

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

\n

编辑:根据建议,下面的代码解决了这个问题

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

lis*_*tdm 6

如果 svg 属性是 a 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>
   );})}
Run Code Online (Sandbox Code Playgroud)