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

主题

Storybook 的 Themes 插件允许你在 Storybook 的预览区域内为组件切换多个主题。

Switching between themes in Storybook

主题 Decorators

为了让你的主题能被 stories 访问,@storybook/addon-themes 暴露了三种针对不同主题化方法的 decorators

JSX Provider

对于通过 provider 向组件暴露主题的库,例如 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 decorator。

.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;

Data 属性

对于依赖父元素上的 data 属性来确定主题的库,你可以使用 withThemeByDataAttribute decorator。

.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;