在没有 dangerouslySetInnerHtml 的情况下在 React JS 中渲染 SVGSVGElement
Render SVGSVGElement in React JS without dangerouslySetInnerHtml
问题:
我可以在不使用 dangerouslySetInnerHtml
的情况下在 React 中渲染 SVGSVGElement
吗?
上下文:
我正在使用 vis.js graph library, the getLegend
method returns an 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 没有帮助:
您可以像这样使用 useRef 简单地附加 SVGSVGElement。此示例适用于带挂钩的功能组件,但可以适用于 class 个组件。
const svg = useRef(null);
useEffect(()=>{
if(svg.current){
svg.current.appendChild(icon)
}
}, []);
return (
<div ref={svg}/>
);
问题:
我可以在不使用 dangerouslySetInnerHtml
的情况下在 React 中渲染 SVGSVGElement
吗?
上下文:
我正在使用 vis.js graph library, the getLegend
method returns an 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 没有帮助:
您可以像这样使用 useRef 简单地附加 SVGSVGElement。此示例适用于带挂钩的功能组件,但可以适用于 class 个组件。
const svg = useRef(null);
useEffect(()=>{
if(svg.current){
svg.current.appendChild(icon)
}
}, []);
return (
<div ref={svg}/>
);