加入在线会议:美国东部时间周四上午 11 点,Storybook 9 版本发布 & AMA
文档
Storybook 文档

模拟提供者

组件可以从上下文提供者(context providers)接收数据或配置。例如,一个 styled component 可能会从 ThemeProvider 访问其主题,或者 Redux 使用 React context 为组件提供应用数据的访问权限。要模拟提供者,你可以将组件包装在一个包含必要上下文的装饰器(decorator)中。

.storybook/preview.tsx
import React from 'react';
 
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Preview } from '@storybook/your-framework';
 
import { ThemeProvider } from 'styled-components';
 
const preview: Preview = {
  decorators: [
    (Story) => (
      <ThemeProvider theme="default">
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </ThemeProvider>
    ),
  ],
};
 
export default preview;

注意上面的文件扩展名(.tsx.jsx)。根据你的项目设置,你可能需要调整预览文件的扩展名以允许使用 JSX。

有关另一个示例,请参考 Storybook 入门教程的屏幕(Screens)章节,我们在其中使用模拟数据模拟了 Redux provider。

配置模拟提供者

模拟提供者时,可能需要配置提供者为单个 story 提供不同的值。例如,你可能希望使用不同的主题或用户角色测试组件。

一种方法是为每个 story 单独定义装饰器。但如果你设想一个场景,希望为你每个组件创建亮色和暗色主题下的 story,这种方法很快就会变得繁琐。

为了更好的方法,且减少重复,你可以使用装饰器函数的第二个“context”参数来访问 story 的parameters 并调整提供的值。通过这种方式,你可以定义一次提供者,并为每个 story 调整其值。

例如,我们可以调整上面的装饰器,使其从 parameters.theme 读取以确定要提供的主题

.storybook/preview.tsx
import React from 'react';
 
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Preview } from '@storybook/your-framework';
 
import { ThemeProvider } from 'styled-components';
 
// themes = { light, dark }
import * as themes from '../src/themes';
 
const preview: Preview = {
  decorators: [
    // 👇 Defining the decorator in the preview file applies it to all stories
    (Story, { parameters }) => {
      // 👇 Make it configurable by reading the theme value from parameters
      const { theme = 'light' } = parameters;
      return (
        <ThemeProvider theme={themes[theme]}>
          <Story />
        </ThemeProvider>
      );
    },
  ],
};
 
export default preview;

现在,你可以在 stories 中定义一个 theme 参数来调整装饰器提供的主题。

Button.stories.ts
// 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>;
 
// Wrapped in light theme
export const Default: Story = {};
 
// Wrapped in dark theme
export const Dark: Story = {
  parameters: {
    theme: 'dark',
  },
};

这种强大的方法允许你以灵活且易于维护的方式,为组件提供任何值(主题、用户角色、模拟数据等)。