如何访问 stenciljs 中的原生 HTML 属性?以及如何让它出现在文档中?
How can I access native HTML attributes in stenciljs? And how to make it appear in the documentation?
用 stenciljs 制作的网络组件不扩展 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.
@Prop()
就像从 标签读取到组件
@Prop({"reflectToAttr": true})
将保持双向绑定并更新两者 - 标记到组件和组件到标记
重要的是要知道您不允许更新您的组件内的@Prop
变量,除非您特别允许它使用可变属性。 @Prop({"mutable": true})
如果您想要两者,只需使用逗号分隔的语法,例如:
@Prop({"mutable": true, "reflectToAttr": true})
详情请看这里:
https://stenciljs.com/docs/properties
我有时会在使用 "title", "focus"
等原生属性时遇到一些问题。正确的方法是在 "data-title", "data-focus"
等属性之前和组件 @Prop() dataTitle
、@Prop() dataFocus
中使用 "data"
。
但老实说,我不喜欢使用 Web 组件的开发人员必须学习特定于 Web 组件的语法,所以我还是使用本机属性。这有时会导致一些您可以轻松修复的错误。但这将是另一个问题的主题。
@Update
我刚刚意识到在较新的 StencilJS 版本中只是 @Prop({"reflect": true})
但想法仍然相同
是的,您不能这样做,但您可以将 HTML 属性直接传递给元素,而无需使用 @Prop
装饰器声明它们。在您的情况下,只需将 title
传递给您的组件。
<your-component title="test title"></your-component>
然后,如果您想读取您的 title 属性的值,您必须先获取对宿主元素的引用。
@Element() host: HTMLElement;
然后,您可以使用宿主元素的 getAttribute 方法读取它,例如:
componentDidLoad() {
const title = this.host.getAttribute('title');
console.log(title); // or do something with it
}
用 stenciljs 制作的网络组件不扩展 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.
@Prop()
就像从 标签读取到组件
@Prop({"reflectToAttr": true})
将保持双向绑定并更新两者 - 标记到组件和组件到标记
重要的是要知道您不允许更新您的组件内的@Prop
变量,除非您特别允许它使用可变属性。 @Prop({"mutable": true})
如果您想要两者,只需使用逗号分隔的语法,例如:
@Prop({"mutable": true, "reflectToAttr": true})
详情请看这里: https://stenciljs.com/docs/properties
我有时会在使用 "title", "focus"
等原生属性时遇到一些问题。正确的方法是在 "data-title", "data-focus"
等属性之前和组件 @Prop() dataTitle
、@Prop() dataFocus
中使用 "data"
。
但老实说,我不喜欢使用 Web 组件的开发人员必须学习特定于 Web 组件的语法,所以我还是使用本机属性。这有时会导致一些您可以轻松修复的错误。但这将是另一个问题的主题。
@Update
我刚刚意识到在较新的 StencilJS 版本中只是 @Prop({"reflect": true})
但想法仍然相同
是的,您不能这样做,但您可以将 HTML 属性直接传递给元素,而无需使用 @Prop
装饰器声明它们。在您的情况下,只需将 title
传递给您的组件。
<your-component title="test title"></your-component>
然后,如果您想读取您的 title 属性的值,您必须先获取对宿主元素的引用。
@Element() host: HTMLElement;
然后,您可以使用宿主元素的 getAttribute 方法读取它,例如:
componentDidLoad() {
const title = this.host.getAttribute('title');
console.log(title); // or do something with it
}