【问题标题】:How can I create instances of customized builtins?如何创建自定义内置插件的实例?
【发布时间】:2021-07-16 10:53:12
【问题描述】:

我正在为 vanilla JS 编写一个 JSX 工厂,但 我似乎无法让自定义的内置函数工作。

如果我定义一个

customElements.define('x-hi', class extends HTMLElement { })

我只能

document.createElement('x-hi')

要获得一个实例,我怎样才能获得这个实例:-

customElements.define('x-hello', class extends HTMLButtonElement { }, { extends: 'button' })

【问题讨论】:

  • 请注意,这在 Safari 中永远不会起作用,因为 Apple 已经声明(5 年来)它不会实现 Customized Built-In 元素.所以只有class extends HTMLElement自治元素)可以跨浏览器工作。
  • @danny-365csi-engelman 这是一个 Electron 应用,别担心

标签: javascript dom custom-element native-web-component


【解决方案1】:
class Hello extends HTMLButtonElement { }
customElements.define('x-hello', Hello, { extends: 'button' });
new (customElements.get('x-hello'))() instanceof Hello
// --> true

您也可以使用普通的自定义元素来执行此操作,但您应该使用document.createElement,因为稍后可能会在代码中定义自定义元素。

你可能在你的工厂里做这样的事情:

const el = document.createElement(tagName);
for (let attrName in attrs) el.setAttribute(attrName, attrs[attrName]);

在已创建的HTMLButtonElement 上将is 设置为x-hello 时,您无法将其原型更改为Hello

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多