文档
Storybook Docs

Parameters

参数是一组关于 story 的静态、命名元数据,通常用于控制 Storybook 功能和插件的行为。

可用参数列在 参数 API 参考 中。

例如,让我们通过一个参数来自定义背景功能。我们将使用 parameters.backgrounds 来定义当选中一个 story 时,背景工具栏中出现的背景。

Story 参数

我们可以在 CSF 导出上使用 parameters 键为单个 story 设置参数

Button.stories.ts|tsx
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta = {
  component: Button,
} satisfies Meta<typeof Button>;
 
export default meta;
type Story = StoryObj<typeof meta>;
 
export const Primary: Story = {
  // 👇 Story-level parameters
  parameters: {
    backgrounds: {
      options: {
        red: { name: 'Red', value: '#f00' },
        green: { name: 'Green', value: '#0f0' },
        blue: { name: 'Blue', value: '#00f' },
      },
    },
  },
};

组件参数

我们可以使用默认 CSF 导出上的 parameters 键为组件的所有 stories 设置参数

Button.stories.ts|tsx
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Meta } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta = {
  component: Button,
  //👇 Creates specific parameters at the component level
  parameters: {
    backgrounds: {
      options: {},
    },
  },
} satisfies Meta<typeof Button>;
 
export default meta;

全局参数

我们还可以通过 .storybook/preview.js|ts 文件中的 parameters 导出为所有 stories 设置参数(这是配置所有 stories 的文件)

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  parameters: {
    backgrounds: {
      options: {
        light: { name: 'Light', value: '#fff' },
        dark: { name: 'Dark', value: '#333' },
      },
    },
  },
};
 
export default preview;

设置全局参数是配置插件的常用方法。通过背景,您可以配置每个 story 可以渲染的背景列表。

参数继承规则

全局、组件和 story 参数的组合方式是

  • 更具体的参数具有更高的优先级(因此 story 参数会覆盖组件参数,组件参数会覆盖全局参数)。
  • 参数是合并的,因此键只会覆盖而不会被丢弃。

参数的合并很重要。这意味着可以为每个 story 覆盖单个特定的子参数,同时保留全局定义的绝大多数参数。

如果您正在定义一个依赖于参数的 API(例如,一个 插件),最好将此行为考虑在内。