HTML5 ES6 自定义元素扩展 HTMLTextAreaElement 导致非法构造函数崩溃



我需要从 HTMLTextAreaElement 扩展一个自定义元素,以便在表单中使用并直接获取值。 但我总是得到非法构造函数消息

.HTML:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div>
      <working-element></working-element>
    </div>
    <div>
      <crashing-element></crashing-element>
    </div>
  </body>
  <script src="myScript.js">
</html>

Typescript(编译为 ES6 到 myScript.js(:

// all works fine
class newElementWorks extends HTMLElement {
  constructor(){
    super();
    console.log('newElementWorks');
  }
}
customElements.define('working-element', newElementWorks);
// this one crashes on super() call
class newElementCrash extends HTMLTextAreaElement {
  constructor(){
    super();
    console.log('newElementCrash');
  }
}
customElements.define('crashing-element', newElementCrash);

该脚本在支持 ES6 和自定义元素的 Chrome 版本 63.0.3239.132 上执行

我完全准备好尝试包含Web组件/自定义元素polyfill。

你知道为什么从 HTML 以外的扩展崩溃吗?

您看到的错误意味着您正在调用new的对象没有[[construct]]的内部方法。

虽然规范表明你可以extend HTML*Element类,但目前似乎不支持它(参见类似的问题:https://github.com/webcomponents/custom-elements/issues/6(,所以你目前只能扩展HTMLElement

在你试图扩展HTMLTextAreaElement时,有两件事是公然错误的。

  1. 注册元素时,必须添加必需参数{ extends: 'textarea' }第三个参数。
  2. 扩展
  3. 内置元素不会获得自己的标记,而是使用扩展元素的标记,将您的名称添加到 is="" 属性中。

class MyTextarea extends HTMLTextAreaElement {
  constructor(){
    super();
    console.log('MyTextarea');
  }
}
customElements.define('my-textarea', MyTextarea, {extends: 'textarea'});
<textarea is="my-textarea"></textarea>

最新更新