LitElement 相当于 React "key" 的概念

LitElement equivalent of React "key" concept

<example name="One"></example>
<example name="Two"></example>
<example name="Three"></example>

下一个渲染看起来像这样:

<example name="Four"></example>
<example name="Three"></example>

LitElement 将删除最后一个元素并使用新属性更新前两个元素。

如何更改此设置,以便 LitElement 删除除 name="three" 之外的所有元素,并在第一个位置创建一个带有 name="Four" 的新元素?

使用 React,这将通过给他们一个密钥 属性 来完成。我想使用 LitElement 获得相同的结果。

<example key="1" name="One"></example>
<example key="2" name="Two"></example>
<example key="3" name="Three"></example>

为此,您要使用 lit-html repeat 指令。来自 the docs:

The repeat directive performs efficient updates of lists based on user-supplied keys:

repeat(items, keyFunction, itemTemplate)

Where:

  • items is an Array or iterable.
  • keyFunction is a function that takes a single item as an argument and returns a guaranteed unique key for that item.
  • itemTemplate is a template function that takes the item and its current index as arguments, and returns a TemplateResult.

For example:

const employeeList = (employees) => html`
  <ul>
    ${repeat(employees, (employee) => employee.id, (employee, index) => html`
      <li>${index}: ${employee.familyName}, ${employee.givenName}</li>
    `)}
  </ul>
`;

If you re-sort the employees array, the repeat directive reorders the existing DOM nodes.

要使用 repeat,您需要从 lit-html:

导入它
import {repeat} from 'lit-html/directives/repeat';