参加直播会话:周四,美国东部时间上午 11 点,Storybook 9 发布和 AMA
文档
Storybook Docs

Actions

Actions 用于在您的故事中显示事件处理程序(回调)参数接收到的数据。

Action args

Actions 通过向您的故事提供 Storybook 生成的特殊“action”参数(简称为“args”)来工作。有两种方法可以获取 action arg

通过 storybook/test fn spy 函数

推荐的编写 actions 的方法是使用 storybook/test 中的 fn 工具来模拟和 spy args。这对于编写交互测试非常有用。您可以通过将组件的方法分配给 fn() 函数来模拟它们

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 { fn } from 'storybook/test';
 
import { Button } from './Button';
 
const meta = {
  component: Button,
  // 👇 Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked
  args: { onClick: fn() },
} satisfies Meta<typeof Button>;
 
export default meta;

如果您的组件调用了一个 arg(无论是用户交互还是 play 函数导致的),并且该 arg 被 spied on,则事件将显示在 action 面板中

Actions usage

自动匹配 args

另一种选择是使用全局参数来匹配符合特定模式的所有 argTypes。以下配置会自动为每个 on argType(您可以手动指定或自动推断)创建 actions。

当您的组件有数十个(甚至数百个)方法并且您不想手动为每个方法应用 fn 工具时,这非常有用。然而,这不是推荐的编写 actions 的方法。这是因为自动推断的 args 在您的 play 函数中不可作为 spies 使用。如果您使用 argTypesRegex 并且您的故事包含 play 函数,您还需要使用 fn 工具定义 args,以便在 play 函数中测试它们。

.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: {
    actions: { argTypesRegex: '^on.*' },
  },
};
 
export default preview;

如果您需要更精细地控制哪些 argTypes 被匹配,您可以调整您的故事并包含 argTypesRegex 参数。例如

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,
  parameters: { actions: { argTypesRegex: '^on.*' } },
} satisfies Meta<typeof Button>;
 
export default meta;

这将一个标准的 HTML 事件处理程序绑定到您的组件渲染的最外层 HTML 元素上,并在针对给定选择器调用事件时触发一个 action。格式为 <eventname> <selector>。选择器是可选的;它默认为所有元素。

API

参数

这将在 actions 命名空间下,为 Storybook 贡献以下参数

argTypesRegex

类型:string

为匹配 regex 的每个 arg 创建 actions。请注意,如上所述,这种方法存在明显的局限性

disable

类型:boolean

禁用 action 面板。

此参数最适用于在更特定的级别上覆盖设置。例如,如果在项目级别将其设置为 true,则可以在 meta(组件)或故事级别将其设置为 false 来重新启用。

导出

import { action } from 'storybook/actions';

action

类型:(name?: string) => void

允许您创建一个 action,当点击时,该 action 会出现在 Storybook UI 的 actions 面板中。action 函数接受一个可选的 name 参数,该参数用于在 UI 中标识该 action。

Button.stories.ts
// 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 { action } from 'storybook/actions';
 
import Button from './Button';
 
const meta = {
  component: Button,
  args: {
    // 👇 Create an action that appears when the onClick event is fired
    onClick: action('on-click'),
  },
} satisfies Meta<typeof Button>;
 
export default meta;