组件 Story 格式 (CSF)
组件故事格式 (CSF) 是编写 故事 的推荐方式。它是一个基于 ES6 模块的 开放标准,可以在 Storybook 之外移植使用。
在 CSF 中,故事和组件元数据被定义为 ES 模块。每个组件故事文件包含一个必需的 默认导出 和一个或多个 命名导出。
默认导出
默认导出定义了组件的元数据,包括 component 本身、它的 title(它将在 导航 UI 故事层次结构 中显示)、装饰器 和 参数。
component 字段是必需的,并且被插件用于自动生成属性表和显示其他组件元数据。title 字段是可选的,并且应该是唯一的(即,不能在文件之间重复使用)。
// 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 { MyComponent } from './MyComponent';
const meta = {
/* 👇 The title prop is optional.
* See https://storybook.org.cn/docs/configure/#configure-story-loading
* to learn how to generate automatic titles
*/
title: 'Path/To/MyComponent',
component: MyComponent,
decorators: [
/* ... */
],
parameters: {
/* ... */
},
} satisfies Meta<typeof MyComponent>;
export default meta;有关更多示例,请参阅 编写故事。
命名故事导出
使用 CSF,文件中的每个命名导出默认代表一个故事对象。
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { MyComponent } from './MyComponent';
const meta = {
component: MyComponent,
} satisfies Meta<typeof MyComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Basic: Story = {};
export const WithProp: Story = {
render: () => <MyComponent prop="value" />,
};导出的标识符将使用 Lodash 的 startCase 函数转换为 "首字母大写" 格式。例如:
| 标识符 | 转换 |
|---|---|
| name | 名称 |
| someName | Some Name |
| someNAME | Some NAME |
| some_custom_NAME | Some Custom NAME |
| someName1234 | Some Name 1 2 3 4 |
我们建议所有导出名称都以大写字母开头。
故事对象可以通过几个不同的字段进行注解,以定义故事级别的 装饰器 和 参数,还可以定义故事的 name。
Storybook 的 name 配置项在特定情况下很有用。常见用例包括带有特殊字符或 JavaScript 受限关键字的名称。如果未指定,Storybook 将默认为命名导出。
// 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 { MyComponent } from './MyComponent';
const meta = {
component: MyComponent,
} satisfies Meta<typeof MyComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Simple: Story = {
name: 'So simple!',
// ...
};Args 故事输入
从 SB 6.0 开始,故事接受称为 Args 的命名输入。Args 是由 Storybook 及其插件提供(并可能更新)的动态数据。
考虑 Storybook 的 "Button" 示例,它是一个记录点击事件的文本按钮。
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { action } from 'storybook/actions';
import { Button } from './Button';
const meta = {
component: Button,
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Basic: Story = {
render: () => <Button label="Hello" onClick={action('clicked')} />,
};现在考虑使用 args 重写的相同示例。
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { action } from 'storybook/actions';
import { Button } from './Button';
const meta = {
component: Button,
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Text = {
args: {
label: 'Hello',
onClick: action('clicked'),
},
render: ({ label, onClick }) => <Button label={label} onClick={onClick} />,
};或者更简单地
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-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 Text: Story = {
args: {},
};这些版本不仅比没有 args 的版本更简短、更易于编写,而且也更具可移植性,因为代码不依赖于 actions 功能本身。
有关设置 文档 和 操作 的更多信息,请参阅 respective documentation。
Play 函数
Storybook 的 play 函数是在故事在 UI 中渲染时执行的小段代码。它们是方便的辅助方法,可以帮助您测试过去不可能实现或需要用户干预的用例。
Play 函数的一个好用例是表单组件。在以前的 Storybook 版本中,您需要编写一系列故事并与组件交互进行验证。使用 Storybook 的 Play 函数,您可以编写如下故事:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { expect } from 'storybook/test';
import { LoginForm } from './LoginForm';
const meta = {
component: LoginForm,
} satisfies Meta<typeof LoginForm>;
export default meta;
type Story = StoryObj<typeof meta>;
export const EmptyForm: Story = {};
export const FilledForm: Story = {
play: async ({ canvas, userEvent }) => {
// 👇 Simulate interactions with the component
await userEvent.type(canvas.getByTestId('email'), 'email@provider.com');
await userEvent.type(canvas.getByTestId('password'), 'a-random-password');
// See https://storybook.org.cn/docs/essentials/actions#automatically-matching-args to learn how to setup logging in the Actions panel
await userEvent.click(canvas.getByRole('button'));
// 👇 Assert DOM structure
await expect(
canvas.getByText(
'Everything is perfect. Your account is ready and we should probably get you started!',
),
).toBeInTheDocument();
},
};当故事在 UI 中渲染时,Storybook 会执行 play 函数中定义的每个步骤,并在无需用户交互的情况下运行断言。
自定义渲染函数
从 Storybook 6.4 开始,您可以通过将故事写成 JavaScript 对象来减少测试组件所需的样板代码,从而提高功能和可用性。Render 函数是为您提供对故事如何渲染的额外控制的有用方法。例如,如果您正在将故事写成一个对象,并且想指定组件应如何渲染,您可以编写以下内容:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { Layout } from './Layout';
import { MyComponent } from './MyComponent';
const meta = {
component: MyComponent,
} satisfies Meta<typeof MyComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
// This story uses a render function to fully control how the component renders.
export const Example: Story = {
render: () => (
<Layout>
<header>
<h1>Example</h1>
</header>
<article>
<MyComponent />
</article>
</Layout>
),
};当 Storybook 加载此故事时,它会检测到 render 函数的存在,并根据定义的内容相应地调整组件渲染。
Storybook 导出与名称处理
Storybook 处理命名导出和 name 选项的方式略有不同。何时应使用其中一个而不是另一个?
Storybook 将始终使用命名导出确定故事 ID 和 URL。
如果您指定了 name 选项,它将在 UI 中用作故事的显示名称。否则,它将默认为命名导出,经过 Storybook 的 storyNameFromExport 和 lodash.startCase 函数处理。
it('should format CSF exports with sensible defaults', () => {
const testCases = {
name: 'Name',
someName: 'Some Name',
someNAME: 'Some NAME',
some_custom_NAME: 'Some Custom NAME',
someName1234: 'Some Name 1234',
someName1_2_3_4: 'Some Name 1 2 3 4',
};
Object.entries(testCases).forEach(([key, val]) => {
expect(storyNameFromExport(key)).toBe(val);
});
});当您想更改故事的名称时,请重命名 CSF 导出。这将更改故事的名称,同时也会更改故事的 ID 和 URL。
在以下情况下使用 name 配置项是最佳选择:
- 您希望故事在 Storybook UI 中的名称以命名导出无法实现的方式显示,例如,保留关键字如 "default",特殊字符如 emoji,以及
storyNameFromExport无法提供的空格/大小写。 - 您希望在不改变显示方式的情况下保留 Story ID。稳定的 Story ID 有助于与第三方工具集成。
非故事导出
在某些情况下,您可能希望导出故事和非故事(例如,模拟数据)的混合。
您可以使用默认导出中的可选配置字段 includeStories 和 excludeStories 来实现这一点。您可以将它们定义为字符串数组或正则表达式。
考虑以下故事文件:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { MyComponent } from './MyComponent';
import someData from './data.json';
const meta = {
component: MyComponent,
includeStories: ['SimpleStory', 'ComplexStory'], // 👈 Storybook loads these stories
excludeStories: /.*Data$/, // 👈 Storybook ignores anything that contains Data
} satisfies Meta<typeof MyComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
export const simpleData = { foo: 1, bar: 'baz' };
export const complexData = { foo: 1, foobar: { bar: 'baz', baz: someData } };
export const SimpleStory: Story = {
args: {
data: simpleData,
},
};
export const ComplexStory: Story = {
args: {
data: complexData,
},
};当此文件在 Storybook 中渲染时,它会将 ComplexStory 和 SimpleStory 视为故事,并忽略 data 命名导出。
对于这个特定的示例,您可以根据方便程度以不同的方式实现相同的结果:
includeStories: /^[A-Z]/includeStories: /.*Story$/includeStories: ['SimpleStory', 'ComplexStory']excludeStories: /^[a-z]/excludeStories: /.*Data$/excludeStories: ['simpleData', 'complexData']
如果您遵循故事导出以大写字母开头(即使用 UpperCamelCase)的最佳实践,则第一个选项是推荐的解决方案。
从 CSF 2 升级到 CSF 3
Storybook 提供了一个 codemod 来帮助您从 CSF 2 升级到 CSF 3。您可以使用以下命令运行它:
npx storybook migrate csf-2-to-3 --glob="**/*.stories.tsx" --parser=tsx在 CSF 2 中,命名导出始终是实例化组件的函数,并且这些函数可以用配置选项进行注解。例如:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { ComponentStory, ComponentMeta } from '@storybook/your-framework';
import { Button } from './Button';
export default {
title: 'Button',
component: Button,
} as ComponentMeta<typeof Button>;
export const Primary: ComponentStory<typeof Button> = (args) => <Button {...args} />;
Primary.args = { primary: true };这会为 Button 声明一个 Primary 故事,该故事通过将 { primary: true } 扩展到组件来渲染自身。default.title 元数据说明了如何在导航层次结构中放置故事。
这是 CSF 3 的等效版本:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-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 = { args: { primary: true } };让我们逐一查看这些更改以了解发生了什么。
可扩展的故事对象
在 CSF 3 中,命名导出是 **对象** 而不是函数。这允许我们使用 JS 展开运算符更有效地重用故事。
考虑对简介示例的以下补充,它创建了一个 PrimaryOnDark 故事,该故事在深色背景下渲染:
这是 CSF 2 的实现:
export const PrimaryOnDark = Primary.bind({});
PrimaryOnDark.args = Primary.args;
PrimaryOnDark.parameters = { background: { default: 'dark' } };Primary.bind({}) 复制了故事函数,但没有复制附加在函数上的注解,因此我们必须添加 PrimaryOnDark.args = Primary.args 来继承 args。
在 CSF 3 中,我们可以展开 Primary 对象来继承其所有注解。
export const PrimaryOnDark: Story = {
...Primary,
parameters: { background: { default: 'dark' } },
};了解更多关于 命名故事导出 的信息。
默认渲染函数
在 CSF 3 中,您通过 render 函数指定故事如何渲染。我们可以通过以下步骤将 CSF 2 示例重写为 CSF 3。
让我们从一个简单的 CSF 2 故事函数开始:
// Other imports and story implementation
export const Default: ComponentStory<typeof Button> = (args) => <Button {...args} />;现在,让我们将其重写为 CSF 3 中的故事对象,并带有显式的 render 函数,该函数告诉故事如何渲染自身。与 CSF 2 一样,这使我们能够完全控制如何渲染组件或组件集合。
// Other imports and story implementation
export const Default: Story = {
render: (args) => <Button {...args} />,
};了解更多关于 渲染函数 的信息。
但在 CSF 2 中,很多故事函数是相同的:它们接收默认导出中指定的组件并将 args 扩展到其中。这些故事中有趣的不是函数本身,而是传入函数的 args。
CSF 3 为每个渲染器提供了默认渲染函数。如果您只是将 args 扩展到您的组件中(这是最常见的情况),则无需指定任何 render 函数。
export const Default = {};有关更多信息,请参阅关于 自定义渲染函数 的部分。
自动生成标题
最后,CSF 3 可以自动生成标题。
export default {
title: 'components/Button',
component: Button,
};export default { component: Button };您仍然可以像 CSF 2 一样指定标题,但如果您不指定,它将从故事在磁盘上的路径推断出来。有关更多信息,请参阅关于 配置故事加载 的部分。
