如何在 decorator 中读取当前 story 的 globals 值并动态注入主题类名

解读

面试官想确认两件事:

  1. 你是否理解 Storybook 的 运行时数据流——globals 与 story 上下文如何传递;
  2. 你是否能在 decorator 这一“无组件”层 拿到 globals 并产生副作用(给 body 或根节点挂类名),而不是在组件内部硬编码。

国内组件库普遍要支持“一键换肤”,设计、产品、测试都在 Storybook 里验收,如果换肤开关不生效,直接视为事故。因此“动态注入主题类名”是高频刚需,也是面试必考点。

知识点

  • globals:Storybook 7 以后的全局变量池,通过 useGlobals() 钩子或 context.globals 访问,不随 story 重新挂载而重置。
  • decorator:本质是“高阶 story”,签名 (Story, context) => JSX.Element,每次 story 渲染都会执行。
  • context 对象:包含 globals、args、argTypes、viewMode、storyFn 等,是 decorator 里取 globals 的唯一官方入口。
  • 副作用注入:必须保证
    – 类名同步时机在 React 渲染 之前(否则会出现闪烁);
    – 清理逻辑在 story 卸载或切换主题时 可靠执行,防止串扰。
  • React 18 StrictMode:在开发环境会 double-render,副作用代码需做 幂等保护。

答案

  1. 在项目根 .storybook/preview.js 里注册全局 decorator:
import { useEffect } from 'react';

export const decorators = [
  (Story, context) => {
    // 1. 取出全局主题变量
    const theme = context.globals.theme || 'light';

    // 2. 副作用:给 body 挂类名,保证在 React 渲染前完成
    useEffect(() => {
      const root = document.body;
      root.classList.remove('theme--light', 'theme--dark');
      root.classList.add(`theme--${theme}`);
      // 清理函数:story 切换或主题变化时自动触发
      return () => root.classList.remove(`theme--${theme}`);
    }, [theme]);

    // 3. 返回原 story
    return <Story />;
  }
];
  1. 在 .storybook/preview.js 中声明全局工具栏开关,方便设计/测试实时切换:
export const globalTypes = {
  theme: {
    name: '主题',
    description: '全局主题切换',
    defaultValue: 'light',
    toolbar: {
      icon: 'mirror',
      items: ['light', 'dark'],
      showName: true,
    },
  },
};
  1. 若使用 Vue3,借助 app.directive 或 provide/inject 同理,在 decorator 里通过 context.globals.theme 取到值后操作 DOM 即可;Angular 则利用 Renderer2 在 applicationConfig 的 decorator 中完成。

关键点:

  • 一定用 context.globals 而不是 window 或参数写死;
  • useEffect 依赖数组写全,防止 React18 StrictMode 下重复添加类名;
  • 清理函数必须返回,否则切 story 时旧主题类名残留,导致视觉验收不通过。

拓展思考

  1. 多主题 token 体系:国内大厂(阿里、腾讯)普遍用 CSS Variables + 类名隔离 实现“主题包”,decorator 里只需切换类名即可,无需重新打包样式,把变量定义在 :root 与 .theme--dark 下即可。
  2. 性能与闪烁:
    • 若主题变量很多,可把类名挂在 #storybook-root 而非 body,减少全局污染;
    • 利用 data-* 属性替代类名,避免 CSS 优先级冲突。
  3. 测试自动化:把主题开关写入 play 函数,结合 @storybook/test-runner 做 视觉回归,一次跑两套截图,防止换肤漏测。
  4. Storybook 8 新特性:globals 将支持 “持久化”,刷新页面后仍保持上次选择,decorator 无需改动即可受益,面试时可主动提及,体现对社区 Roadmap 的关注。