参数
参数是一组关于 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;
全局参数
我们还可以通过你的 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(例如插件),最好考虑这种行为。