【发布时间】:2020-02-04 02:18:09
【问题描述】:
所以我知道如何创建自定义元素并且已经制作了 2 个我很满意的元素。 我的两个元素看起来像这样:
let menuPicker = Object.create(HTMLElement.prototype);
menuPicker.initialized = false;
menuPicker._init = function(){
...
}
...
menuPicker.attachedCallback = menuPicker._init;
menuPicker.createdCallback = menuPicker._init;
...
document.registerElement('menu-picker', {
prototype: menuPicker
});
这很有效,但这次我想要一个 JS 类。特别是这个功能:
class test {
get item(){...}
set item(){...}
}
所以我想我可以执行以下操作来轻松实现这一点。
class listBox extends HTMLElement.prototype {
initialized = false;
constructor(props){
super(props);
this.attachedCallback = this._init;
this.createdCallback = this._init;
}
_init () {
if(this.initialized) return;
this.initialized = true;
this.style.display = "block";
this.appendChild(document.createElement('div'));
}
}
document.registerElement('list-box', {
prototype: listBox
});
但是我收到错误 Class extends value #<HTMLElement> is not a constructor or null。
所以现在我被卡住了,找不到使用类来构造自定义 HTML 元素的方法。
为了简化:
如何使用 JS 类创建自定义元素来创建元素的属性?
【问题讨论】:
-
这感觉像是一个可以通过阅读developer.mozilla.org/en-US/docs/Web/Web_Components/…来避免的问题
-
oml :P 当我第一次学习如何创建元素时,我确实读过那篇文章。 TYSM 将我重定向到那里。我觉得自己像个白痴。
-
有时会发生。可能值得再次删除问题=)
-
错误是由
class listBox extends HTMLElement.prototype这行引起的。应该是class listBox extends HTMLElement。
标签: javascript html class custom-element