在React JS中渲染SVGSVGElement而不使用dangerouslySetInnerHtml

mai*_*mas 6 javascript svg reactjs 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>
Run Code Online (Sandbox Code Playgroud)

问题:

当我尝试使用以下方法渲染时:

render (
<div> { icon } </div>
)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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`
Run Code Online (Sandbox Code Playgroud)

解决方法:

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

但是我希望有一个直截了当的解决方案,它不会在名称中使用带有危险一词的方法.

研究:

我读了这个类似的问题,但我不认为它对运行时生成的SVG有帮助:如何在不使用dangerouslySetInnerHTML的情况下在React中使用SVG?

小智 6

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

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

return (
    <div ref={svg}/>
);
Run Code Online (Sandbox Code Playgroud)