如何访问 stenciljs 中的原生 HTML 属性?以及如何让它出现在文档中?

amo*_*uda 2 javascript web-component typescript stenciljs

使用 stenciljs 制作的 Web 组件不扩展 HTMLElement。我如何访问本机属性并在我的组件中使用它们,比如title属性?当我@Prop() title在模板中添加并使用它时,会显示错误。

添加@Prop()还会使属性在生成的文档中可见。如何将使用的或必需的本机属性添加到生成的文档中?

我得到的编译器错误:

The @Prop() name "title" is a reserved public name. Please rename the "title" prop so it does not conflict
with an existing standardized prototype member. Reusing prop names that are already defined on the element's
prototype may cause unexpected runtime errors or user-interface issues on various browsers, so it's best to
avoid them entirely.
Run Code Online (Sandbox Code Playgroud)

Mic*_*mpl 6

是的,您不能这样做,但是您可以将 HTML 属性直接传递给元素,而无需使用@Prop装饰器声明它们。在您的情况下,只需传递title给您的组件。

<your-component title="test title"></your-component>
Run Code Online (Sandbox Code Playgroud)

然后,如果您想读取 title 属性的值,则必须首先获取对宿主元素的引用。

@Element() host: HTMLElement;
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用宿主元素的 getAttribute 方法读取它,例如:

componentDidLoad() {
  const title = this.host.getAttribute('title');
  console.log(title); // or do something with it
}
Run Code Online (Sandbox Code Playgroud)