Stencil驼峰式@Prop在Storybook中不生效,如何保留驼峰写法解决?
解决Stencil驼峰式@Prop在Storybook中失效的问题
问题场景
开发Stencil组件并编写Storybook故事时,全小写的@Prop(如label)能正常接收值,但驼峰式@Prop(如inputId)无法生效。尝试过在模板中使用驼峰式和短横线式属性名,均未解决问题,只有将Prop改为全小写才能正常工作。
Stencil组件代码
import {Component, Prop, h} from '@stencil/core'; @Component({ tag: 'text-input', shadow: true, }) export class TextInput { @Prop() label: string; @Prop() inputId: string; render() { return ( <div class="text-input"> <label htmlFor={this.inputId}>{this.label}</label> <input type="text" id={this.inputId} /> </div> ) } }
原Storybook故事代码(存在问题)
export default { title: 'Components/Text Input', argTypes: { label: {control: 'text'}, inputid : {control: 'text'}, } }; const Template = (args) => { let tag = `<text-input label="${args.label}" inputId="${args.inputid}"></text-input>`; return tag }; export const Default = Template.bind({}); Default.args = { label: 'First name:', inputid: 'Input1' };
解决方案
要保留Stencil组件的驼峰式@Prop并让Storybook正常工作,需调整两处:
- 统一Storybook参数的命名为驼峰式:Storybook的
argTypes和args中的参数名必须和Stencil组件的@Prop驼峰名完全一致,不能用全小写。 - 在HTML模板中使用短横线式属性名:HTML属性不区分大小写,Stencil会自动将短横线式(kebab-case)属性映射到组件类中的驼峰式(camelCase)
@Prop。
修改后的Storybook代码
export default { title: 'Components/Text Input', argTypes: { label: {control: 'text'}, // 改为驼峰式inputId,与组件Prop一致 inputId : {control: 'text'}, } }; const Template = (args) => { // 使用短横线式input-id,Stencil会自动映射到inputId Prop let tag = `<text-input label="${args.label}" input-id="${args.inputId}"></text-input>`; return tag }; export const Default = Template.bind({}); Default.args = { label: 'First name:', // 改为驼峰式inputId inputId: 'Input1' };
原理说明
Stencil遵循Web组件规范,自动处理属性名的大小写映射:
- 组件类中定义的驼峰式Prop(如
inputId),在HTML中需要用短横线式(input-id)传递值 - Storybook的参数系统需要和组件Prop的命名严格对应(驼峰式),确保参数值能正确传递到模板,再通过短横线属性映射到组件Prop
内容的提问来源于stack exchange,提问作者Ilya Shunko
相关产品推荐
相关产品推荐

