However I get the error Class extends value #<HTMLElement> is not a constructor or null.So now I'm stuck and can't find a method of using a class to construct a custom HTML element.
To simplify:
解决方案
Here is an example to create a custom element
//ListBox.js
export default class ListBox extends HTMLElement {
// observe attributes of custom element
static get observedAttributes() {
return ["disp", "text"];
}
get myAction() {
return this.hasAttribute("open");
}
set myAction(val) {
if (val) {
this.setAttribute("open", "");
} else {
this.removeAttribute("open");
}
}
constructor() {
super();
this.initialized = false;
this.div = document.createElement("div");
// get and assigns value from props "disp"
this.div.style.display = this.getAttribute("disp");
// get and assigns value from props "text"
this.div.innerHTML = this.getAttribute("text");
this.appendChild(this.div);
}
connectedCallback() {
// didMount
// your methode here
this.initialized = true;
console.log("custom element added to page");
}
disconnectedCallback() {
// unmount
console.log("custom element remove from page");
}
attributeChangedCallback(name, oldValue, newValue) {
// observed props
console.log("props", arguments);
// get and assigns value from props "text"
if (name === "text" && oldValue !== newValue) {
this.div.innerHTML = newValue;
}
}
}
in your html in the script tag which calls your index.js add type="module"
In your index.js import your component and do Something
import ListBox from "./component/ListBox";
customElements.define("list-box", ListBox);
// change props "text value"
document
.querySelector("list-box")
.setAttribute("text", `Change the value of props "text"`);