You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中使用{@html}无法在<svg>内插入<polygon>的解决咨询

Svelte动态插入SVG元素不渲染的解决方法

问题场景

父组件代码:

<script>
    import ObjOne from './ObjOne.svelte'
</script>

<svg width="182px" height="146px" viewBox="0 0 182 146">
    <ObjOne></ObjOne>
</svg>

ObjOne组件代码:

<script>
  let html = '<polygon id="Path" fill="#999999" points="109.9999 146.25 109.9999 98.75 182.4999 98.75 182.4999 146.25" />'
</script>

{@html html}

上述代码中,通过{@html}动态插入的<polygon>无法渲染,只有直接将<polygon>写入组件主体时才能正常显示。尝试给<svg>添加version和xmlns属性也无效,需要找到动态插入SVG元素的可行方案。

核心原因

SVG元素必须属于SVG命名空间(http://www.w3.org/2000/svg)才能被SVG容器识别,而{@html}会把字符串解析为HTML命名空间下的元素,不属于SVG命名空间,因此无法渲染。

可行解决方案

方案1:手动创建SVG命名空间元素并添加

通过绑定SVG元素引用,在脚本中创建符合SVG命名空间的元素,再添加到SVG容器中。

修改父组件,绑定SVG元素引用:

<script>
    import ObjOne from './ObjOne.svelte';
    let svgElement;
</script>

<svg width="182px" height="146px" viewBox="0 0 182 146" bind:this={svgElement}>
    <ObjOne svgRef={svgElement}></ObjOne>
</svg>

修改ObjOne组件,创建并插入元素:

<script>
  import { onMount } from 'svelte';
  
  export let svgRef;
  
  onMount(() => {
    if (!svgRef) return;
    
    // 创建SVG命名空间下的polygon元素
    const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
    polygon.setAttribute('id', 'Path');
    polygon.setAttribute('fill', '#999999');
    polygon.setAttribute('points', '109.9999 146.25 109.9999 98.75 182.4999 98.75 182.4999 146.25');
    
    svgRef.appendChild(polygon);
  });
</script>

方案2:用Svelte原生动态渲染(推荐)

如果动态内容结构可预测,直接用Svelte的模板语法动态生成元素,Svelte会自动处理SVG命名空间。

ObjOne组件修改为:

<script>
  // 定义多边形属性
  let polygonProps = {
    id: 'Path',
    fill: '#999999',
    points: '109.9999 146.25 109.9999 98.75 182.4999 98.75 182.4999 146.25'
  };
</script>

<polygon {...polygonProps} />

如果需要渲染多个动态元素,可使用{#each}循环:

<script>
  // 定义多个图形数据
  let shapes = [
    {
      type: 'polygon',
      props: {
        id: 'Path',
        fill: '#999999',
        points: '109.9999 146.25 109.9999 98.75 182.4999 98.75 182.4999 146.25'
      }
    }
  ];
</script>

{#each shapes as shape}
  {#if shape.type === 'polygon'}
    <polygon {...shape.props} />
  {/if}
{/each}

内容的提问来源于stack exchange,提问作者Nikolay Dyankov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:54:25