主题
Storybook 的 主题 插件允许你在 Storybook 中的预览中为组件切换多个主题。
¥Storybook's Themes addon allows you to switch between multiple themes for your components inside of the preview in Storybook.
主题装饰器
¥Theme decorators
为了使你的主题可用于你的故事,@storybook/addon-themes
公开了三个 decorators 以用于不同的主题方法。
¥To make your themes accessible to your stories, @storybook/addon-themes
exposes three decorators for different methods of theming.
JSX 提供程序
¥JSX providers
对于通过提供程序向组件公开主题的库,例如 Material UI、Styled-components 和 情感,请使用 withThemeFromJSXProvider
。
¥For libraries that expose themes to components through providers, such as Material UI, Styled-components, and Emotion, use the withThemeFromJSXProvider
.
// Replace your-renderer with the framework you are using (e.g., react, vue3)
import { Preview, Renderer } from '@storybook/your-renderer';
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 classes
对于依赖父元素上的 CSS 类来确定主题的库,你可以使用 withThemeByClassName
装饰器。
¥For libraries that rely on CSS classes on a parent element to determine the theme, you can use the withThemeByClassName
decorator.
// Replace your-renderer with the framework you are using (e.g., react, vue3)
import { Preview, Renderer } from '@storybook/your-renderer';
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 attributes
对于依赖父元素上的数据属性来确定主题的库,你可以使用 withThemeByDataAttribute
装饰器。
¥For libraries that rely on data attributes on a parent element to determine the theme, you can use the withThemeByDataAttribute
decorator.
// Replace your-renderer with the framework you are using (e.g., react, vue3)
import { Preview, Renderer } from '@storybook/your-renderer';
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;