LitElement不会为本地Web组件设置textContent

时间:2019-12-23 21:38:08

标签: javascript web-component lit-element lit-html native-web-component

我已经构建了一个名为<textarea>的本地Web组件,该组件扩展了<expanding-textarea>content goes here</expanding-textarea>的功能。我可以设置<textarea>${item.text}</textarea>之类的组件的文本内容,但是当我尝试通过使用LitElement中的组件来动态设置内容时,则无法设置。以下是一个最小的示例,该示例正确地为重复指令中的<body> <my-element></my-element> <script type="module"> const template = document.createElement("template"); template.innerHTML = `<textarea></textarea>`; class ExpandingTextarea extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template.content.cloneNode(true)); const textarea = this.shadowRoot.querySelector("textarea"); textarea.textContent = this.textContent; } } customElements.define("expanding-textarea", ExpandingTextarea); import { LitElement, html } from "lit-element"; import { repeat } from "lit-html/directives/repeat.js"; class MyElement extends LitElement { static get properties() { return { list: { type: Array }, }; } constructor() { super(); this.list = [ { id: "1", text: "hello" }, { id: "2", text: "hi" }, { id: "3", text: "cool" }, ]; } render() { return html` ${repeat( this.list, item => item.id, item => html`<expanding-textarea>${item.text}</expanding-textarea>` )} `; } } customElements.define("my-element", MyElement); </script> </body> 填充了文本,但不是按原样填充。

------------ Master --------------
ID | Master_Number | First_Arrival

1 个答案:

答案 0 :(得分:0)

问题在于this.textContentconstructor()中没有值,因为<expanding-textarea>尚未在DOM中。仅在将this.textContent连接到DOM后,<expanding-textarea>才有价值。因此,将ExpandingTextarea更改为

class ExpandingTextarea extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
  connectedCallback() {
    const textarea = this.shadowRoot.querySelector("textarea");
    textarea.textContent = this.textContent;
  }
}

您可以在Stackblitz(https://stackblitz.com/edit/expanding-textarea?file=my-element.js)上看到它