Chi*_*dex 3 javascript arrays svg object reactjs
我正在开发一个 React 项目,并且尝试从对象数组中渲染 SVG。然而,每当我尝试从地图方法访问 SVG 时,我都会收到错误。有没有更好的方法来完成我所缺少的过程。对于上下文:
\nlocations: [\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 ]\nRun Code Online (Sandbox Code Playgroud)\nSVG 已在此处作为 React 组件导入。
\njsx中的用法:
\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 })}\nRun Code Online (Sandbox Code Playgroud)\n将location.svg记录到控制台会返回这种性质的对象
\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 })}\nRun Code Online (Sandbox Code Playgroud)\n
如果 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)
| 归档时间: |
|
| 查看次数: |
2021 次 |
| 最近记录: |