lit-element: appendChild элемента ul в constructor () отображается в неправильной позиции dom

  • Попытка создать инкапсулированный список задач с освещенными элементами. В качестве первого шага пытаемся создать элемент ul, а затем добавлять элемент li при каждом нажатии кнопки.
  • Хотя я могу заставить это работать, начав с предварительного создания элемента привязки ul в html перед веб-компонентом, я не хочу этого делать. Я хочу, чтобы вся функциональность содержалась в веб-компоненте.
  • Below is a consolidated html file (including the lit-element script), showing a couple of ways that I've attempted this.
    • If I create the ul element in the constructor, then I'm successfully able to append li elements. But, they are in the wrong position (after other elements that come after the component in the html portion).
    • Если я создаю элемент ul в литерале html-шаблона функции render (), то нажатие кнопки не работает (что приводит к ошибке «uncaught typeerror, невозможно прочитать свойство appendChild со значением null»).

Почему эти реализации не работают? Я даже попытался разбить его на 2 разных веб-компонента, где первый компонент отвечает только за создание ul, но я получаю ту же ошибку «appendChild of null».

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <p>(1) from html - before litelement component</p>
  <raf-demo></raf-demo>
  <p>(2) from html - after litelement component</p>
</body>

<script type="module">
  import { LitElement, html, css } from 'https://unpkg.com/lit-element/lit-element.js?module';

  class rafDemo extends LitElement {
    constructor() {
      super();
      var el = document.createElement("ul");
      el.id = "button1";
      el.innerHTML = "Why after (2)? From the component constructor(), I need something that fires only once and renders before render(), outputting between (1) and (2).";
      document.body.appendChild(el); 
    }
    render() {
      return html`
      <ul id="button2">from component in render() - correctly renders inbetween</ul>
      <button @click="${this.button1}">Add li: works, but after (2)</button>
      <button @click="${this.button2}">Add li: should be between (1) and (2), but error</button>
      `;
    }
    button1(event) {
      const li = document.createElement('li');
      li.textContent = "text";
      document.getElementById('button1').appendChild(li);
    }
    button2(event) {
      const li = document.createElement('li');
      li.textContent = "text";
      document.getElementById('button2').appendChild(li);
    }
  }
  customElements.define('raf-demo', rafDemo);
</script>
</html>

Ваша помощь очень ценится!


person eadgbe    schedule 10.03.2020    source источник


Ответы (1)


person    schedule
comment
Ах. this.shadowRoot.getElementById ('button2'). Много узнать о лит-элементах. Большое спасибо! - person eadgbe; 10.03.2020
comment
Это очень выиграет от некоторого объяснения @CelimpiloMncwango :) - person SRack; 11.03.2020