【问题标题】:Getting error while creating a custom element which extends SVGCircleElement创建扩展 SVGCircleElement 的自定义元素时出错
【发布时间】:2020-08-23 17:19:46
【问题描述】:

我有以下 Node 类,用于创建自定义元素 node-element

class Node extends SVGCircleElement{
    static get observedAttributes() {
        return ["coordinates"];
      }
    constructor()
    {
        super();
        this.attributeMap = {coordinates:(coordinates)=>this.updateCoordinates(coordinates)}
    }
    connectedCallback(){
        this.initNode();
    }
    updateCoordinates(coordinates)
    {
        this.setAttribute("cx",`${coordinates.x}`);
        this.setAttribute("cy",`${coordinates.y}`);
        this.setAttribute("r",50);
    }
    initNode()
    {
        this.className="node";
    }
    attributeChangedCallback(name,oldValue,newValue)
    {
        if(oldValue!==newValue)
        {
            this.attributeMap[name](JSON.parse(newValue))
        }
    }
}

我使用以下方法注册此元素:-

customElements.define('node-element',Node);

我正在按如下方式创建此元素:-

let newNode = document.createElement("node-element");

这是我得到以下错误的地方:-

Uncaught TypeError: Illegal constructor
    at new Node (index.js:9)
    at SVGSVGElement.drawNode (index.js:43)

第 43 行对应 createElement 代码。

【问题讨论】:

  • 请尝试使用document.createElementNS
  • 你能告诉我如何将它与“node-element”一起使用吗?
  • 您是否成功扩展(其他)SVG 元素?
  • @enxaneta 我尝试了 document.createElementNS("w3.org/2000/svg","node-element")。这没有给出错误,但没有调用任何构造函数或生命周期方法。我使用控制台日志对其进行了验证。
  • @Danny'365CSI'Engelman 我的要求是只使用圆形元素,所以我只扩展了它的类。

标签: javascript svg web-component custom-element


【解决方案1】:

很想被证明是错误的,刚刚在一个 SVG 项目上花了 2 个月时间

AFAIK,你不能扩展 SVG 元素

您只能在 HTML 命名空间 http://www.w3.org/1999/xhtml 中创建自定义元素

SVG 元素位于 SVG 命名空间 http://www.w3.org/2000/svg

来自文档:https://html.spec.whatwg.org/multipage/custom-elements.html#element-definition

如果extends的元素接口和HTML命名空间是HTMLUnknownElement,
然后抛出“NotSupportedError”DOMException。

如果命名空间不是 HTML 命名空间,则返回 null

正在进行的关于允许其他命名空间的 W3C 讨论在这里:https://github.com/w3c/webcomponents/issues/634


HTML 命名空间也有限制

Apple/Safari 实现了 自治自定义元素(从 HTMLElement 扩展)

但拒绝实现自定义内置元素(从 HTML 命名空间扩展任何内置元素)


如果你想生成SVG,你必须扩展HTMLElement并生成整个SVG标签:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='V'><circle cx='X' cy='Y' r='R'/></svg>

相关的自定义元素 SVG StackOverflow 问答

【讨论】:

  • Aww 射人。感谢您澄清这一点。我有一个很大的 svg 元素,每当我单击 svg 内的任何点时,我都想在其中绘制各种节点(圆圈)。我能够在 div 上使用绝对定位来实现此功能,但我知道 svg 更适合这样的东西,但没有自定义元素支持很烂。
  • 所以,回到 oldskool,您可以执行 createElement('circle') 并将其附加到 SVG。或者将其创建为 String 并在现有 SVG 组 &lt;g&gt; 上设置 innerHTML
  • 最后一个链接循环回到这里。
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 2017-02-20
  • 2014-09-20
  • 2019-12-11
  • 2023-03-27
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多