javascript - 在 React JS 中渲染 SVGSVGElement,无需危险设置InnerHtml

标签 javascript reactjs svg vis.js

问题: 我可以渲染 SVGSVGElement在 React 中不使用 dangerouslySetInnerHtml

上下文:

我正在使用vis.js图形库,getLegend方法返回 SVGSVGElement 对象,即 const icon = chart.getLegend(args); 在控制台中我可以看到:

in: icon instanceof SVGSVGElement
out: true
in: icon
out: <svg><rect x="0" y="0" width="30" height="30" class="vis-outline"></rect><path class="vis-graph-group0" d="M0,15 L30,15"></path></svg>

问题:

当我尝试使用以下方式在 React 中渲染它时:

render (
<div> { icon } </div>
)

我收到以下错误:

Error: Objects are not valid as a React child (found: [object SVGSVGElement]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `LegendElement`

解决方法:

现在我正在使用: <svg dangerouslySetInnerHTML={{__html: icon.innerHTML}} />

但我希望有一个简单的解决方案,不使用名称中含有“危险”一词的方法。

研究:

我读过这个类似的问题,但我认为它对运行时生成的 SVG 没有帮助:How do I use an SVG in React without using dangerouslySetInnerHTML?

最佳答案

您可以像这样使用 useRef 简单地附加 SVGSVGElement。此示例适用于带有钩子(Hook)的功能组件,但可以适用于类组件。

const svg = useRef(null);
useEffect(()=>{
    if(svg.current){
        svg.current.appendChild(icon)
    } 
}, []);

return (
    <div ref={svg}/>
);

关于javascript - 在 React JS 中渲染 SVGSVGElement,无需危险设置InnerHtml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45877087/

相关文章:

node.js - 使用 nextjs 应用程序注册 service worker

javascript - 固定定位溢出不滚动

javascript - 使用 for 循环加载 Jssor Slider

javascript - 如何从 React 组件中渲染整个树?

javascript - 如何用简单的例子来理解 `interpolateTransformCss` 中的 `interpolateTransformSvg` 、 `d3-interpolate` ?

css - 用颜色填充 SVG 路径但悬停淡入模式

java - 在Java中使用文档鼠标单击修改SVG文件

javascript - 使用 D3JS 的和弦 DHT 图表

javascript - 如何将 HTML 中显示的数字格式化为货币格式,包括 $ 符号并使用 <sup></sup> 放置小数?

css - 将 Tailwind 类转换为 css 内联样式