我正在使用一个函数来构建父SVG标签,然后根据状态值生成子“圆圈” svg组件。
安装组件时出现以下错误
Objects are not valid as a React child (found: [object SVGSVGElement]). If
you meant to render a collection of children, use an array instead.
这是功能
buildSVG = () => {
const { overlays } = this.state;
const NS = 'http://www.w3.org/2000/svg';
const svgOverlay = document.createElementNS(NS, 'svg');
svgOverlay.id = 'svg_overlays';
svgOverlay.classList.add('overlay');
Object.keys(overlays).forEach((el) => {
const circle = document.createElementNS(NS, 'circle');
circle.setAttribute('cx', overlays[el].cx);
circle.setAttribute('cy', overlays[el].cy);
circle.setAttribute('r', overlays[el].r);
circle.setAttribute('fill', overlays[el].fill);
svgOverlay.appendChild(circle);
});
return svgOverlay;
}
理想情况下,这将导致svg及其子级出现,在这种情况下,它将引发错误。
答案 0 :(得分:0)
buildSVG = () => {
const { overlays } = this.state;
const circleArray = [];
Object.keys(overlays).forEach((el) => {
const circle = (
<circle
key={overlays[el].cx + overlays[el].cy + overlays[el].fill}
cx={overlays[el].cx}
cy={overlays[el].cy}
r={overlays[el].r}
stroke={overlays[el].fill}
strokeWidth="4"
fill="blue"
/>
);
circleArray.push(circle);
});
return (
<svg
id="svg_overlays"
className="overlay"
onClick={this.handleClickOverlay}
onDragOver={this.handleOverlayDragOver}
onDrop={this.handleOverlayDrop}
>
{circleArray}
</svg>
);
}