【问题标题】:How can I add style prop as control in Storybook?如何在 Storybook 中添加样式道具作为控件?
【发布时间】:2021-07-05 03:42:24
【问题描述】:

我正在使用 Storybook 在 React 和 TypeScript 中构建设计系统库。大多数组件支持使用 style 属性设置自定义样式。我正在尝试使用 Controls 功能在 Storybook 中反映这一点。

考虑以下带有变体并尝试添加样式道具的 Button 故事:

// Button.stories.js

import { Button } from './button';

export default {
  component: Button,
  title: 'Button',
  argTypes: {
    variant: {
      control: {
        type: 'radio',
        options: ['primary', 'secondary']
      }
    },
    style: {
      control: {
        type: 'text'
      },
      defaultValue: '{marginBottom: 10}'
    }
  }
};

当样式道具的类型是React.CSSProperties 时,我应该使用什么正确的控件类型? defaultValue 的正确格式是什么?

【问题讨论】:

    标签: reactjs typescript storybook


    【解决方案1】:

    正如docs中所建议的:

    默认情况下,Storybook 会根据 arg 的 initial 值为每个 arg 选择一个控件。

    要在 React 中使用自动检测控件,您必须填写故事元数据中的 组件 字段:

    例如:

    import { Button } from './Button';
    
    export default {
      title: 'Button',
      component: Button, // Here
    };
    

    Storybook 使用它根据PropTypes(使用react-docgen)或TypeScript 类型(使用react-docgen-typescript)为您的组件自动生成ArgType。

    因此,要自动生成style 控件,您可以编写:

    export default {
      component: Button, // This is must
      title: 'Button',
      argTypes: {
        variant: {
          control: {
            type: 'radio',
            options: ['primary', 'secondary']
          }
        },
        style: {                             // Remove the control type
          defaultValue: { marginBottom: 10 } // Keep it as object
        }
      }
    };
    

    这是一个快照:

    【讨论】:

      【解决方案2】:

      这是@AjeetShah 答案的更新版本,如果上述内容不适合您。

      button.stories.jsx

      export default {
        component: Button, 
        title: 'Button',
          argTypes{
             style: {
              name: 'style',
              defaultValue: {},
              type: { name: 'style', required: false },
              table: {
                type: {
                  summary: 'StyleProp',
                  detail: null,
                },
                defaultValue: { summary: '' },
              },
              control: {
                type: 'object',
              },
            }
          }
        }
      

      Screenshot of the above using an sx prop

      package.json

      "@storybook/addon-essentials": "6.3.12",
      "@storybook/react": "6.3.12"
      

      .storybook/main.js

      module.exports = {
        stories: [
          '../path/to/my/stories/*.stories.jsx',
        ],
        addons: [
          '@storybook/addon-essentials',
        ],
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2020-05-06
        • 2022-06-18
        • 2020-10-19
        • 2010-09-22
        • 1970-01-01
        • 2021-03-25
        • 2021-07-01
        • 2020-07-28
        相关资源
        最近更新 更多