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

问题描述 投票:0回答:2

我需要从 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 和 Custom-Element 的 Chrome 版本 63.0.3239.132 上执行

我已经尝试包含web组件/自定义元素polyfill

你知道为什么从 HTMLElement 以外的地方扩展会崩溃吗?

javascript html typescript ecmascript-6 custom-element
2个回答
6
投票

您看到的错误意味着您正在调用

new
的对象没有
[[construct]]
内部方法。

虽然规范表明您可以

extend
HTML*Element 类,但目前似乎不支持(请参阅类似的问题:https://github.com/webcomponents/custom-elements/issues/6 )所以此时你只能延长
HTMLElement


3
投票

您尝试延长

HTMLTextAreaElement
时有两件事是不正确的。

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

class MyTextarea extends HTMLTextAreaElement {
  constructor(){
    super();
    console.log('MyTextarea');
  }
}

customElements.define('my-textarea', MyTextarea, {extends: 'textarea'});
<textarea is="my-textarea"></textarea>

© www.soinside.com 2019 - 2024. All rights reserved.