Skip to content

Storybook 速查表

用于隔离构建与测试组件的 UI 组件工作台。

01

快速上手

Story

用 CSF 格式定义 story。

storybook
import type { Meta, StoryObj } from "@storybook/react";
import Button from "./Button";

const meta: Meta<typeof Button> = {
  title: "Button",
  component: Button,
};
export default meta;

type Story = StoryObj<typeof Button>;
export const Primary: Story = {
  args: { primary: true, label: "Click" },
};

Controls

用 Controls 交互式调整 props。

storybook
export const Default: Story = {
  args: {
    label: "Button",
    size: "md",
  },
  argTypes: {
    size: { control: "select", options: ["sm", "md", "lg"] },
  },
};
02

核心特性

装饰器

装饰器包裹 story。

storybook
export const WithPadding: Story = {
  decorators: [(Story) => <div style={{padding: 20}}><Story /></div>],
};

Play 函数

Play 函数用于交互测试。

storybook
export const Interactive: Story = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole("button"));
    await expect(canvas.getByText("Clicked")).toBeInTheDocument();
  },
};

这篇内容对您有帮助吗?