加入直播会话:周四 EDT 上午 11 点,Storybook 9 发布及 AMA
返回集成
styled-components

集成Styled Components与 Storybook

Styled Components 是一个 css-in-js 框架,用于构建快速且实用的组件。
前提条件

本配方假设你已经有一个使用 styled-components 的 React 应用,并且刚刚使用入门指南设置了 Storybook >=7.0。没有这些?请按照 styled-components 的安装说明进行操作,然后运行

# Add Storybook:
npm create storybook@latest

1. 添加 @storybook/addon-themes

运行以下脚本来安装并注册该插件

npx storybook@latest add @storybook/addon-themes

这将运行一个配置脚本,引导你完成插件的设置。当提示时,从配置选项中选择 styled-components

配置脚本失败了吗?

在底层,这运行 npx @storybook/auto-config themes,它应该会读取你的项目并尝试使用正确的装饰器配置你的 Storybook。如果直接运行该命令无法解决你的问题,请在 @storybook/auto-config 仓库上提交一个错误报告,以便我们进一步改进它。要手动添加此插件,请安装它,然后将其添加到 .storybook/main.ts 中的 addons 数组。

2. 提供 GlobalStyles

.storybook/preview.js 中,创建一个包含 font-family<GlobalStyles /> 组件。然后通过将其添加到 decorators 数组,使用 withThemeFromJSXProvider 装饰器将其应用于你的 story。

// .storybook/preview.jsx
 
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
import { createGlobalStyle } from 'styled-components';
 
const GlobalStyles = createGlobalStyle`
  body {
    font-family: "Nunito Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  }
`;
 
export const decorators = [
  withThemeFromJSXProvider({
    GlobalStyles, // Adds your GlobalStyle component to all stories
  }),
];

如果你的应用中已经有 <GlobalStyles />,你可以将其导入 .storybook/preview.js,而不是重新创建。

3. 提供你的主题(们)

要将你的主题(们)分享给 Storybook 中的组件,你需要将它们与 styled-components<ThemeProvider /> 组件一起提供给 withThemeFromJSXProvider 装饰器。

// .storybook/preview.jsx
 
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
 
import { lightTheme, darkTheme } from '../src/themes';
 
/* snipped for brevity */
 
export const decorators = [
  withThemeFromJSXProvider({
  themes: {
    light: lightTheme,
    dark: darkTheme,
  }
  defaultTheme: 'light',
  Provider: ThemeProvider,
  GlobalStyles,
})];

当你提供多个主题时,Storybook UI 中会出现一个工具栏菜单,用于选择你的 story 想要使用的主题。

参与其中

现在你已经准备好将 styled-components 与 Storybook 一起使用了。🎉

如果你在工作中使用 styled-components,我们非常希望你能帮助让这个设置变得更容易。加入 Discord 的维护者社区参与其中,或者查阅插件文档

标签
贡献者
  • ShaunEvening
    ShaunEvening