[英]React - Using svg <defs> with dangerouslySetInnerHTML
I am trying to use svg
with <defs>
defined elsewhere in the page.我正在尝试将svg
与页面中其他地方定义的<defs>
一起使用。
const data = {
icons: {
freezable: "<svg><path d=""/></svg>",
vegetarian: "<svg><path d=""/></svg>",
}
};
const SvgDefs = (icons) => {
return Object.keys(icons).map(iconName => {
return <span key={data.icons[iconName]} dangerouslySetInnerHTML={{
__html: data.icons[iconName].replace('svg', `svg id="svg-${iconName}"`)
}} />;
});
};
With my component rendering this as:我的组件将其渲染为:
return <svg aria-hidden="true" id="svgdefs" xmlns="http://www.w3.org/2000/svg">
<defs>
<SvgDefs icons={data.icons} />
</defs>
</svg>
However, when I check the Elements tab in Chrome Dev Tools, I see that the spans containing the svgs are outside of the <defs>
block:但是,当我检查 Chrome 开发工具中的 Elements 选项卡时,我看到包含 svgs 的跨度在<defs>
块之外:
What am I doing wrong here?我在这里做错了什么?
The problem comes from you calling your functional component's input argument icons
, and the assumptions that stem from that naming choice.问题来自您调用功能组件的输入参数icons
,以及源自该命名选择的假设。
Functional components are passed JSX properties wrapped up in an object, conventionally called props
, so call your function input props
and then get your data back out from that.功能组件通过包裹在 object 中的 JSX 属性传递,通常称为props
,因此调用您的 function 输入props
,然后从中获取数据。 Since you passed icons=...
, you'll need access that data through props.icons
:由于您通过了icons=...
,您需要通过props.icons
访问该数据:
const SvgDefs = (props) => {
const { icons } = props;
return Object.entries(icons).map(([name, html]) => {
return <span key={name} dangerouslySetInnerHTML={{
__html: html.replace('svg', `svg id="svg-${name`)
}} />;
});
};
Although it would make a lot more sense to not have SVG strings in your data.icons to begin with: just have more JSX so you don't need to dangerously set innerHTML at all.虽然在你的 data.icons 中没有 SVG 字符串会更有意义:只要有更多的 JSX,所以你根本不需要危险地设置 innerHTML。
I discovered that the reason was because <span>
cannot be used inside <defs>
.我发现原因是因为<span>
不能在<defs>
中使用。 I used <symbol>
instead and all worked as expected.我改用<symbol>
并且一切都按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.