首页 > 解决方案 > 如何在 Storybook 6.0 中自定义深色和浅色主题

问题描述

我正在使用明暗主题制作 PWA,我想创建我的 Storybook 明暗主题来反映这些主题。

所以我创建了一个函数,如果我向它传递一个 Material UI Theme 和一个基本名称,它将返回一个新的 Storybook 主题对象。

但是如何将这两个对象作为主题传递给 Storybook?

我发现我应该去manager.js添加以下代码

import theme from '../src/theme/theme'
import createThemeFromMUITheme from './create-theme-from-mui-theme'
import addons from '@storybook/addons'

addons.setConfig({
  theme: createThemeFromMUITheme('light', theme.light),
})

但是如何为明暗设置主题?

我努力了

import theme from '../src/theme/theme'
import createThemeFromMUITheme from './create-theme-from-mui-theme'
import addons from '@storybook/addons'

addons.setConfig({
  theme: {
    light: createThemeFromMUITheme('light', theme.light),
    dark: createThemeFromMUITheme('dark', theme.dark)
  },
})

但这使得故事书什么也没有显示(但它并没有失败)

请帮忙 :-)

编辑:我也尝试了以下

import theme from '../src/theme/theme'
import createThemeFromMUITheme from './create-theme-from-mui-theme'
import addons from '@storybook/addons'

addons.setConfig({
  theme: createThemeFromMUITheme('light', theme.light),
})

addons.setConfig({
  theme: createThemeFromMUITheme('dark', theme.dark),
})

编辑#2:从 createThemeFromMUITheme 返回的主题配置对象是有效的顺便说一句

如果有人想要我制作的将 MUI 主题对象转换为 SB 主题对象的功能 - 那么就是这样......

(我还没有弄乱表格颜色......)

import { create } from '@storybook/theming/create'

const createThemeFromMUITheme = (name, theme) => {
  return create({
    base: name,

    colorPrimary: theme.palette.primary.main,
    colorSecondary: theme.palette.secondary.main,

    // UI
    appBg: theme.palette.background.default,
    appContentBg: theme.palette.background.paper,
    appBorderColor: theme.palette.background.paper,
    appBorderRadius: theme.shape.borderRadius,

    // Typography
    fontBase: theme.typography.fontFamily,
    fontCode: 'monospace',

    // Text colors
    textColor: theme.palette.text.primary,
    textInverseColor: theme.palette.text.secondary,

    // Toolbar default and active colors
    barTextColor: theme.palette.text.primary,
    barSelectedColor: theme.palette.text.secondary,
    barBg: theme.palette.background.default,

    brandTitle: 'Add your brand title here',
    brandUrl: 'https://yourbrandurl.com',
    brandImage: 'https://placehold.it/350x150',
  })
}

export default createThemeFromMUITheme

标签: storybook

解决方案


默认情况下,您只能为您的故事书显示一个主题,但您可以使用名为 storybook-dark-mode 的插件在深色和浅色主题之间切换,这是此处的插件页面

一个例子把它放在 preview.js 文件中:


import { addParameters } from '@storybook/react'; // or any other type of storybook

addParameters({
  darkMode: {
    // Set the initial theme
    current: 'light'
    // Override the default dark theme
    dark: { ...themes.dark, appBg: 'black' },
    // Override the default light theme
    light: { ...themes.normal, appBg: 'red' }
  }
});

然后你的故事书中会有一个像这样的切换按钮

在此处输入图像描述


推荐阅读