我需要从 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 以外的地方扩展会崩溃吗?
您看到的错误意味着您正在调用
new
的对象没有 [[construct]]
内部方法。
虽然规范表明您可以
extend
HTML*Element 类,但目前似乎不支持(请参阅类似的问题:https://github.com/webcomponents/custom-elements/issues/6 )所以此时你只能延长HTMLElement
。
您尝试延长
HTMLTextAreaElement
时有两件事是不正确的。
{ extends: 'textarea' }
第三个参数。is=""
属性中添加您的名字。class MyTextarea extends HTMLTextAreaElement {
constructor(){
super();
console.log('MyTextarea');
}
}
customElements.define('my-textarea', MyTextarea, {extends: 'textarea'});
<textarea is="my-textarea"></textarea>