javascript - 从对象渲染 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记录到控制台会返回这种性质的对象
- {$$typeof: Symbol(react.forward_ref), render: ƒ}$$typeof: Symbol(react.forward_ref)render: ƒ SvgSanfrancisco({ title, titleId, ...props }, svgRef)displayName: (... )get displayName: ƒ ()set displayName: ƒ (name)arguments: (...)caller: (...)length: 1name: "set"prototype: {constructor: ƒ} proto : ƒ ()[[FunctionLocation ]]: react.development.js:1401[[Scopes]]: Scopes[4] proto : Object...*
是否可以通过对象访问 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>
);
})}
解决方案
如果 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>
);})}
推荐阅读
- regex - 我该如何编写这个 modsecurity 规则?
- node.js - 使用 apollo-upload-client 时如何在上传文件中设置 utf-8 编码?
- python - Python Dataframe 通过名称指定令人满意的行
- html - 页面正文的可滚动高度不随屏幕宽度(视差)调整
- keycloak - React + keycloak-js:kc.updateToken() 不起作用:由于“未定义”刷新令牌,Keycloak 返回 400
- aws-lambda - 在无服务器框架中使用预定义角色
- r - 当通过element_markdown在ggplot2中部分加粗标题并使用officeR粘贴到powerpoint时,单词不对齐
- javascript - 如何创建可以修改其原始函数调用的对象
- verilog - 使用 Xilinx 7 系列和 Verilog 中的 CARRY4 使 4 位加法器适合单个片
- r - 如何在ggplot2中将虚线长度设置为小于1?