定义组件

通过创建一个扩展 LitElement 的类并使用浏览器注册您的类来定义 Lit 组件。

@customElement 装饰器是调用 customElements.define 的简写,它使用浏览器注册自定义元素类,并将其与元素名称(在本例中为 simple-greeting)关联。

如果您使用的是 JavaScript,或者您没有使用装饰器,您可以直接调用 define()

当您定义 Lit 组件时,您实际上是在定义一个 自定义 HTML 元素。因此,您可以像使用任何内置元素一样使用新元素。

LitElement 基类是 HTMLElement 的子类,因此 Lit 组件继承了所有标准 HTMLElement 属性和方法。

具体而言,LitElement 继承自 ReactiveElement,后者实现了响应式属性,并进而继承自 HTMLElement

Inheritance diagram showing LitElement inheriting from ReactiveElement, which in turn inherits from HTMLElement. LitElement is responsible for templating; ReactiveElement is responsible for managing reactive properties and attributes; HTMLElement is the standard DOM interface shared by all native HTML elements and custom elements.

TypeScript 会根据标签名称推断从某些 DOM API 返回的 HTML 元素的类。例如,document.createElement('img') 返回一个 HTMLImageElement 实例,它具有 src: string 属性。

自定义元素可以通过以下方式添加到 HTMLElementTagNameMap 来获得相同的处理。

通过这样做,以下代码将正确进行类型检查。

我们建议为所有在 TypeScript 中编写的元素添加 HTMLElementTagNameMap 条目,并确保在您的 npm 包中发布您的 .d.ts 类型定义。