文档
Storybook Docs

主题

Storybook 的 Themes 插件允许您在 Storybook 的预览环境中切换组件的多种主题。

Switching between themes in Storybook

主题装饰器

为了让您的故事可以访问这些主题,@storybook/addon-themes 提供了三种用于不同主题方法的 装饰器

JSX 提供者

对于通过提供者将主题暴露给组件的库,例如 Material UIStyled-componentsEmotion,请使用 withThemeFromJSXProvider

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import { Preview, Renderer } from '@storybook/your-framework';
 
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
 
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { lightTheme, darkTheme } from '../src/themes';
 
const GlobalStyles = createGlobalStyle`
  body {
    font-family: "Nunito Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  }
`;
 
const preview: Preview = {
  decorators: [
    withThemeFromJSXProvider<Renderer>({
      themes: {
        light: lightTheme,
        dark: darkTheme,
      },
      defaultTheme: 'light',
      Provider: ThemeProvider,
      GlobalStyles,
    }),
  ],
};
 
export default preview;

CSS 类

对于依赖父元素上的 CSS 类来确定主题的库,您可以使用 withThemeByClassName 装饰器。

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import { Preview, Renderer } from '@storybook/your-framework';
 
import { withThemeByClassName } from '@storybook/addon-themes';
 
import '../src/index.css'; // Your application's global CSS file
 
const preview: Preview = {
  decorators: [
    withThemeByClassName<Renderer>({
      themes: {
        light: '',
        dark: 'dark',
      },
      defaultTheme: 'light',
    }),
  ],
};
 
export default preview;

数据属性

对于依赖父元素上的数据属性来确定主题的库,您可以使用 withThemeByDataAttribute 装饰器。

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import { Preview, Renderer } from '@storybook/your-framework';
 
import { withThemeByDataAttribute } from '@storybook/addon-themes';
 
import '../src/index.css'; // Your application's global CSS file
 
const preview: Preview = {
  decorators: [
    withThemeByDataAttribute<Renderer>({
      themes: {
        light: 'light',
        dark: 'dark',
      },
      defaultTheme: 'light',
      attributeName: 'data-theme',
    }),
  ],
};
 
export default preview;