在React中使用SVG内的脚本标签?



我有一些svg内部配备了脚本(用于处理onClick事件),如:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="200" height="200">
<defs>
<linearGradient id="borderColor" x1="0%" y1="0%" x2="90%" y2="70%">
<stop stop-opacity="0.8" stop-color="#def0ff" offset="0"/>
<stop stop-opacity="0.8" stop-color="#9bb0c2" offset="0.3"/>
<stop stop-opacity="0.8" stop-color="#def0ff" offset="0.4"/>
<stop stop-opacity="0.8" stop-color="#9bb0c2" offset="0.6"/>
<stop stop-opacity="0.8" stop-color="#def0ff" offset="0.7"/>
<stop stop-opacity="0.8" stop-color="#9bb0c2" offset="1"/>
</linearGradient>
<linearGradient x1="0" y1="0" x2="0.9" y2="0.7" id="fillColor">
<stop stop-opacity="0.4" stop-color="#dbdfe2" offset="0"/>
<stop stop-opacity="0.4" stop-color="#d8d8e1" offset="0.3"/>
<stop stop-opacity="0.4" stop-color="#c9ced3" offset="0.3"/>
<stop stop-opacity="0.5" stop-color="#dae2e9" offset="0.6"/>
<stop stop-opacity="0.5" stop-color="#e3e9ed" offset="0.6"/>
<stop stop-opacity="0.5" stop-color="#e2e9ed" offset="1"/>
</linearGradient>
<radialGradient id="circleGrad">
<stop offset="0%" stop-color="black" />
<stop offset="100%" stop-color="white" />
</radialGradient>
<mask id="myMask">
<rect width="100%" height="100%" fill="white"/>
<circle cx="20" cy="180" r="20" 
fill="url(#circleGrad)"/>

<circle cx="100" cy="20" r="20" 
fill="url(#circleGrad)"/>

<circle cx="180" cy="180" r="20" 
fill="url(#circleGrad)"/>
</mask>


<radialGradient id="circleGrad2">
<stop offset="0%" stop-color="white" />
<stop offset="100%" stop-color="black" />
</radialGradient>
<mask id="myMask2">
<rect width="100%" height="100%" fill="black"/>
<circle cx="20" cy="180" r="20" 
fill="url(#circleGrad2)"/>

<circle cx="100" cy="20" r="20" 
fill="url(#circleGrad2)"/>

<circle cx="180" cy="180" r="20" 
fill="url(#circleGrad2)"/>
</mask>
</defs>

<script  type="application/ecmascript"><![CDATA[
function triangle_click(evt){
const fgPath = evt.target;
const newVal = fgPath.getAttribute('stroke-dasharray') === '0' ? '30 20' : 0;
fgPath.setAttribute('stroke-dasharray',newVal);
}
]]> </script>

<path d="M 20,180 L 100,20 L 180,180 Z" 
stroke="#00ffff" stroke-width="3" 
fill="url(#fillColor)"
mask="url(#myMask2)">
<animate 
attributeName="stroke-dashoffset"
values="0;500"
dur="5s"
repeatCount="indefinite"
/>
</path>

<path id="fgPath" d="M 20,180 L 100,20 L 180,180 Z" 
stroke="url(#borderColor)" stroke-width="3" 
stroke-dasharray="0"
stroke-linecap="round"
fill="url(#fillColor)"
mask="url(#myMask)"
onclick="triangle_click(evt)"
>
<animate 
attributeName="stroke-dashoffset"
values="0;500"
dur="5s"
repeatCount="indefinite"
/>
</path>
</svg>

现在,当我将这个SVG添加到我的react应用程序时,它会在'onClick'事件上抛出错误,除非我复制并粘贴<script>标签在检查器中,任何地方(Uncaught ReferenceError: triangle_click is not defined at onclick).

这是否意味着这个脚本标签最初没有被读取,这就是为什么它没有在第一处找到它?

谢谢,M

我发现问题是我插入元素作为innerHTML。答案可以在这里找到:执行

相关内容

  • 没有找到相关文章

最新更新