我如何使用JS类创建自定义元素来创建元素的属性

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

所以我知道如何创建自定义元素,并且已经制作了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。特别是此功能:

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类创建自定义元素来创建元素的属性?

javascript html class custom-element
1个回答
0
投票

这里是创建自定义元素的示例

  //ListBox.js
  export default class ListBox extends HTMLElement {
  // observe attributes of custom element
  static get observedAttributes() {
    return ["initialized", "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;
    }
  }
}

在您的HTML中的脚本标签中调用了index.js,添加了type =“ module”

<!DOCTYPE html>
<html>
  <head>
  </head>

  <body>
    <div id="app"></div>
    <list-box text="Some text here" disp="block"></list-box>
    <script src="src/index.js" type="module"></script>
  </body>
</html>

在index.js中,导入组件并执行某些操作

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"`);
© www.soinside.com 2019 - 2024. All rights reserved.