组件 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 功能本身。
有关设置 Docs 和 Actions 的更多信息,请参阅各自的文档。
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提供的不同之外的间距/大小写。 - 您希望将故事 ID 与其显示方式分开。稳定的故事 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 一样指定标题,但如果您不指定,则可以从磁盘上的故事路径推断出来。有关更多信息,请参阅 配置故事加载 部分。
