问题:
我可以渲染 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/