React中SVG内动态Circle组件无法渲染问题求助
问题原因与解决方案
问题出在SVG内部不能嵌套HTML的<div>元素——SVG属于XML命名空间,仅支持SVG标准内的元素(如circle、g、path等),HTML元素放在SVG中会被浏览器忽略,导致包裹在<div>里的动态circle无法被渲染,即便你的cx、cy值是正确的。
修复方案1:直接移除包裹的<div>
不需要额外容器的话,直接返回map生成的circle列表即可:
<div className='canvas'> <svg width="700px" height="350px"> <circle cx="690" cy="10" r="10" fill={"blue"} /> <circle cx="10" cy="10" r="10" fill={"green"} /> <circle cx="10" cy="340" r="10" fill={"blue"} /> <circle cx="690" cy="340" r="10" fill={"green"} /> {circles.length > 0 ? circles.map((e, index) => { console.log("-----------", e[0], e[1]); return <circle key={index} cx={e[0]} cy={e[1]} r="10" fill={"blue"} />; }) : null } </svg> </div>
修复方案2:用SVG的<g>标签分组(如需统一控制)
如果需要对动态生成的circle做统一样式、变换等操作,用SVG标准的<g>(组)标签代替<div>:
<div className='canvas'> <svg width="700px" height="350px"> <circle cx="690" cy="10" r="10" fill={"blue"} /> <circle cx="10" cy="10" r="10" fill={"green"} /> <circle cx="10" cy="340" r="10" fill={"blue"} /> <circle cx="690" cy="340" r="10" fill={"green"} /> {circles.length > 0 ? <g> {circles.map((e, index) => { console.log("-----------", e[0], e[1]); return <circle key={index} cx={e[0]} cy={e[1]} r="10" fill={"blue"} />; })} </g> : null } </svg> </div>
内容的提问来源于stack exchange,提问作者Varun Pandey
相关产品推荐
相关产品推荐

