You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于全局主题参数切换Storybook故事背景色?

实现Storybook全局主题切换body背景色

要根据context.globals中的主题值为所有故事全局设置body背景色,通过全局装饰器就能实现,具体操作如下:

1. 定义主题与背景色的映射关系

先把不同主题对应的背景色整理成映射对象:

const themeBackgroundMap = {
  [MyTheme.Light]: '#ffffff',
  [MyTheme.Dark]: '#1a1a1a'
};

2. 添加全局装饰器

在.storybook/preview.js(或.preview.ts)文件中,添加全局装饰器,读取当前主题并动态设置body背景色:

export const decorators = [
  (Story, context) => {
    // 获取当前主题对应的背景色,默认用浅色主题的颜色
    const currentBg = themeBackgroundMap[context.globals.theme] || themeBackgroundMap[MyTheme.Light];
    // 直接设置body的背景色
    document.body.style.backgroundColor = currentBg;

    // 渲染故事内容
    return <Story />;
  }
];

3. 可选:添加样式清理逻辑

如果担心样式污染,可以在装饰器中加入清理逻辑,确保故事卸载时恢复原始背景色(以React为例):

import { useEffect } from 'react';

export const decorators = [
  (Story, context) => {
    const currentBg = themeBackgroundMap[context.globals.theme] || themeBackgroundMap[MyTheme.Light];
    // 保存原始背景色
    const originalBgColor = document.body.style.backgroundColor;
    
    document.body.style.backgroundColor = currentBg;

    // 组件卸载时恢复原始样式
    useEffect(() => {
      return () => {
        document.body.style.backgroundColor = originalBgColor;
      };
    }, []);

    return <Story />;
  }
];

当你在工具栏切换主题时,context.globals.theme会同步更新,装饰器会重新执行,body背景色也会自动切换。

内容的提问来源于stack exchange,提问作者magnattic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:25:40