组件故事格式 (CSF)
观看视频教程
组件故事格式 (CSF) 是编写故事的推荐方式。它是一个基于 ES6 模块的开放标准,可移植到 Storybook 之外。
如果您使用旧的 storiesOf()
语法编写了故事,它在 Storybook 8.0 中已被移除,并且不再维护。我们建议您将故事迁移到 CSF。请参阅迁移指南了解更多信息。
在 CSF 中,故事和组件元数据定义为 ES 模块。每个组件故事文件都包含一个必需的默认导出和一个或多个命名导出。
默认导出
默认导出定义了有关组件的元数据,包括组件本身、其标题(它将在导航 UI 故事层级结构中显示的位置)、装饰器和参数。
该 component
字段是必需的,并且插件使用它来自动生成属性表并显示其他组件元数据。该 title
字段是可选的,并且应该是唯一的(即,不要在文件中重复使用)。
// Replace your-framework with the name of your framework
import type { Meta } from '@storybook/your-framework';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
/* 👇 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: { ... },
};
export default meta;
有关更多示例,请参阅编写故事。
命名故事导出
使用 CSF,文件中的每个命名导出默认表示一个故事对象。
import type { Meta, StoryObj } from '@storybook/react';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const Basic: Story = {};
export const WithProp: Story = {
render: () => <MyComponent prop="value" />,
};
导出的标识符将使用 Lodash 的 startCase 函数转换为“首字母大写”格式。例如
标识符 | 转换 |
---|---|
name | Name |
someName | Some Name |
someNAME | Some NAME |
some_custom_NAME | Some Custom NAME |
someName1234 | Some Name 1 2 3 4 |
我们建议所有导出名称都以大写字母开头。
故事对象可以使用一些不同的字段进行注释,以定义故事级别的装饰器和参数,以及定义故事的名称。
Storybook 的 name
配置元素在特定情况下很有用。常见用例是包含特殊字符或 Javascript 受限词的名称。如果未指定,Storybook 默认使用命名导出。
// Replace your-framework with the name of your framework
import type { Meta, StoryObj } from '@storybook/your-framework';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const Simple: Story = {
decorators: [],
name: 'So simple!',
parameters: {},
};
参数故事输入
从 SB 6.0 开始,故事接受名为参数的命名输入。参数是 Storybook 及其插件提供(并可能更新)的动态数据。
考虑 Storybook 的“按钮”示例,它是一个文本按钮,可以记录其点击事件
import type { Meta, StoryObj } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Basic: Story = {
render: () => <Button label="Hello" onClick={action('clicked')} />,
};
现在考虑使用参数重写的同一个示例
import type { Meta, StoryObj } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Text = {
args: {
label: 'Hello',
onClick: action('clicked'),
},
render: ({ label, onClick }) => <Button label={label} onClick={onClick} />,
};
甚至可以更简单
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Text: Story = {
args: {},
};
这些版本不仅比它们的非参数对应版本更短、更易于编写,而且由于代码不依赖于操作插件,因此也更具可移植性。
有关设置文档和操作的更多信息,请参阅其各自的文档。
播放功能
Storybook 的 play
函数是 UI 中故事渲染时执行的小段代码片段。它们是方便的辅助方法,可帮助您测试原本不可能或需要用户干预的用例。
表单组件是 play
函数的一个很好的用例。在以前的 Storybook 版本中,您需要编写故事集并与组件交互以验证它。使用 Storybook 的播放功能,您可以编写以下故事
import type { Meta, StoryObj } from '@storybook/react';
import { userEvent, within, expect } from '@storybook/test';
import { LoginForm } from './LoginForm';
const meta: Meta<typeof LoginForm> = {
component: LoginForm,
};
export default meta;
type Story = StoryObj<typeof LoginForm>;
export const EmptyForm: Story = {};
/*
* See https://storybook.org.cn/docs/writing-stories/play-function#working-with-the-canvas
* to learn more about using the canvasElement to query the DOM
*/
export const FilledForm: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// 👇 Simulate interactions with the component
await userEvent.type(canvas.getByTestId('email'), '[email protected]');
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
函数是帮助您进一步控制故事渲染方式的辅助方法。例如,如果您将故事编写为对象并希望指定组件的渲染方式,则可以编写以下内容
import type { Meta, StoryObj } from '@storybook/react';
import { Layout } from './Layout';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
// 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”)、特殊字符(如表情符号)、与
storyNameFromExport
提供的不同的空格/大小写。 - 您希望独立于显示方式保留故事 ID。拥有稳定的故事 ID 有助于与第三方工具集成。
非故事导出
在某些情况下,您可能希望导出故事和非故事的混合(例如,模拟数据)。
您可以在默认导出中使用可选的配置字段 includeStories
和 excludeStories
来实现这一点。您可以将它们定义为字符串或正则表达式的数组。
考虑以下故事文件
import type { Meta, StoryObj } from '@storybook/react';
import { MyComponent } from './MyComponent';
import someData from './data.json';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
includeStories: ['SimpleStory', 'ComplexStory'], // 👈 Storybook loads these stories
excludeStories: /.*Data$/, // 👈 Storybook ignores anything that contains Data
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
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
在 CSF 2 中,命名导出始终是实例化组件的函数,并且这些函数可以用配置选项进行注释。例如
import { ComponentStory, ComponentMeta } from '@storybook/react';
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 等价物
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
const meta: Meta<typeof Button> = { component: Button };
export default meta;
type Story = StoryObj<typeof Button>;
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
以继承参数。
在 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 中,许多故事函数是相同的:获取默认导出中指定的组件并将参数传播到其中。这些故事的有趣之处不在于函数,而在于传递给函数的参数。
CSF 3 为每个渲染器提供默认渲染函数。如果您只是将参数传播到组件中(这是最常见的情况),则根本不需要指定任何 render
函数
export const Default = {};
有关更多信息,请参阅有关 自定义渲染函数 的部分。
自动生成标题
最后,CSF 3 可以自动生成标题。
export default {
title: 'components/Button',
component: Button,
};
export default { component: Button };
您仍然可以像在 CSF 2 中一样指定标题,但如果您没有指定标题,则可以从磁盘上故事的路径推断出来。有关更多信息,请参阅关于配置故事加载的部分。