使用 Storybook 渲染多个变体

问题描述 投票:0回答:2

我正在为使用 React 构建的库构建故事书文档,但我没有找到在同一页面中呈现多个变体的简单方法。

所以,到目前为止我所拥有的是这样的

const Template = (args, { argTypes }) => <Title {...args} />

export const Primary = Template.bind({});
export const Success = Template.bind({});
export const Warning = Template.bind({});
export const Inverse = Template.bind({});
export const Default = Template.bind({});
export const Info = Template.bind({});
export const Danger = Template.bind({});
export const Disabled = Template.bind({});

Primary.args = {
  children: 'Primary',
  level: 3, // <- this can go from 1 to 5,
  as: 'h1', 
  variant: 'primary',
}

Success.args = {
  children: 'Success',
  level: 3, // <- this can go from 1 to 5,
  as: 'h1',
  variant: 'success',
}

等等...

这会生成:

enter image description here

当我渲染每个变体时,我试图实现这样的目标:

enter image description here

我怎样才能用 Storybook 做类似的事情?

javascript reactjs storybook
2个回答
10
投票

您可以使用

decorators

在故事中渲染组件的多个实例

示例代码(应该与您的代码类似):

export const Primary = Template.bind({});
Primary.args = {
  primary: true,
  label: 'Button',
};

Primary.decorators = [
  () => {
    return (
      <>
        <Button {...Primary.args as ButtonProps} level={1} />
        <Button {...Primary.args as ButtonProps} level={2} />
        <Button {...Primary.args as ButtonProps} level={3} />
      </>
    );
  },
];

输出:

enter image description here

更多info,有3个级别的

decorators
,值得一读:

  1. 故事级别
  2. 组件级别
  3. 全球水平

0
投票

任何在 Vue 上苦苦挣扎的人,这里是如何在一个故事中实现多个变体的示例:

export const AllColors: Story = {
  render: (args) => ({
    components: { Button },
    setup() {
      return { args }
    },
    template: `
      <div class="flex items-center gap-4">
        <Button v-bind="args" color="primary" />
        <Button v-bind="args" color="warning" />
        <Button v-bind="args" color="danger" />
        <Button v-bind="args" color="secondary" />
        <Button v-bind="args" color="success" />
      </div>
    `
  })
}

其中

args
是这个故事的全局参数

© www.soinside.com 2019 - 2024. All rights reserved.