2

我已经构建了一个名为的本机 Web 组件<expanding-textarea>,它扩展了<textarea>. <expanding-textarea>content goes here</expanding-textarea>当我尝试通过使用 LitElement 中的组件动态设置内容时,我可以设置组件的文本内容,但不能。下面是一个最小的示例,它<textarea>${item.text}</textarea>在重复指令中正确填充文本,但不是按原样填充。

<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>
4

1 回答 1

2

问题是它在 DOM 中没有this.textContent任何价值。只有在连接到 DOM 后才会有价值。所以改为constructor()<expanding-textarea>this.textContent<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 )上看到这一点

于 2019-12-25T22:44:44.597 回答