You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Storybook 6.5.9中Web Components数组属性传递失败求助

问题解决:Stencil组件在Storybook中无法接收数组属性

问题原因

HTML原生属性仅支持字符串类型,你当前通过模板字符串传递数组时,数组会被隐式转为字符串"some,thing",而Stencil的@Prop默认不会自动将字符串解析为数组,再加上你的items定义为String[]类型,类型不匹配时Stencil会回退到默认的空数组,导致组件无法接收到正确数据。

解决方案

方案1:通过JS方式创建组件并设置属性(推荐)

直接用JavaScript创建组件元素,绕过HTML属性的字符串限制,直接设置JS属性:

import { Story, Meta } from '@storybook/html';

export default {
  title: 'Components/TestComponent',
  parameters: {
    options: {
      showPanel: true
    },
  }
} as Meta;

const Template: Story = (args) => {
  const component = document.createElement('test-component');
  // 直接设置JS属性,而非HTML属性
  component.items = args.items;
  return component;
};

export const Default = Template.bind({});
// 定义默认参数
Default.args = {
  items: ['some', 'thing']
};

方案2:将数组转为JSON字符串传递

如果坚持使用模板字符串写法,需要将数组序列化为JSON字符串,同时修改组件的@Prop配置以支持自动解析:

组件代码修改:

import {Component, Host, h, Prop} from '@stencil/core';

@Component({
  tag: 'test-component',
})
export class TestComponent {
  /**
   * Array of options for the group.
   */
  // 添加type和reflect配置,让Stencil自动解析JSON字符串为数组
  @Prop({ reflect: true, type: Array }) items?: string[] = [];

  render() {
    return (
      <Host>
        {this.items.map(item => (
          <h1>{item}</h1>
        ))}
      </Host>
    )
  }
}

Story代码修改:

import { Story, Meta } from '@storybook/html';

export default {
  title: 'Components/TestComponent',
  parameters: {
    options: {
      showPanel: true
    },
  }
} as Meta;

const Template: Story = (args) => {
  // 将数组转为JSON字符串,用单引号包裹避免双引号冲突
  return `
    <test-component items='${JSON.stringify(args.items)}'>
    </test-component>
  `;
};

export const Default = Template.bind({});
Default.args = {
  items: ['some', 'thing']
};

补充说明

布尔、字符串、数字类型属性能正常工作,是因为HTML属性可以将这些类型的字符串表示自动转为对应的JS类型(比如"true"转为布尔值true),但数组/对象没有对应的原生HTML属性表示方式,必须通过JS属性传递或手动序列化解析。

内容的提问来源于stack exchange,提问作者JV Lobo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:06:17