如何在Stencil组件中应用未用@Prop声明的剩余Props?
在Stencil中获取未声明@Prop的剩余Props并传递给原生元素
要实现类似React中剩余属性展开的效果,你可以通过Stencil的@Element()装饰器结合组件元数据,自动收集未用@Prop声明的属性,再传递给内部的<button>元素。
方案1:手动维护已声明Prop集合(适合少量Prop的组件)
import { Component, Prop, h, Element } from '@stencil/core'; @Component({ tag: 'core-button', }) export class CoreButton { @Element() el: HTMLElement; @Prop() name: string; render() { // 列出所有已用@Prop声明的属性名 const declaredProps = new Set(['name']); const restProps: Record<string, string> = {}; // 遍历组件元素的所有属性,过滤掉已声明的Prop Array.from(this.el.attributes).forEach(attr => { if (!declaredProps.has(attr.name)) { restProps[attr.name] = attr.value; } }); return ( <button name={`example ${this.name}`} {...restProps}> <slot /> </button> ); } }
方案2:自动获取已声明Prop(适合多Prop的组件)
通过getComponentMetadata函数可以自动提取组件中所有@Prop的定义,无需手动维护集合:
import { Component, Prop, h, Element, getComponentMetadata } from '@stencil/core'; @Component({ tag: 'core-button', }) export class CoreButton { @Element() el: HTMLElement; @Prop() name: string; // 可添加更多@Prop属性,无需手动更新集合 render() { // 获取组件元数据,提取所有@Prop的名称 const componentMeta = getComponentMetadata(CoreButton); const declaredProps = new Set(componentMeta.props.map(prop => prop.name)); const restProps: Record<string, string> = {}; Array.from(this.el.attributes).forEach(attr => { if (!declaredProps.has(attr.name)) { restProps[attr.name] = attr.value; } }); return ( <button name={`example ${this.name}`} {...restProps}> <slot /> </button> ); } }
关键说明
@Element()装饰器用于获取当前组件的DOM元素实例,通过它可以访问所有传入的HTML属性。- 两种方案都会过滤掉已用
@Prop声明的属性,只将剩余属性传递给内部的<button>,实现和React中...props相同的效果。 - 对于布尔属性(如
disabled)、样式属性(如class/style),Stencil会自动处理其值的转换,无需额外编码。
内容的提问来源于stack exchange,提问作者Sam Scolari
相关产品推荐
相关产品推荐

