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

Storybook 6.5(Twig模板)如何将全局工具栏选中的类型传递给组件参数

Storybook 6.5(Twig模板)如何将全局工具栏选中的类型传递给组件参数

嘿,你已经搞定了工具栏开关和组件wrapper加类的部分,很棒!其实不用搞那个复杂的事件监听,Storybook本身就有更直接的方式把全局选中的类型传递给Twig组件的参数,我给你两种方案参考:

方案一:在单个故事的渲染函数中直接传递

你可以在故事的渲染函数里同时接收args和context参数,然后把全局选中的类型合并到args里再传给Twig模板。修改你的MyComponent.stories.js:

import MyComponent from "./MyComponent.twig";

export default {
  title: "Components/My Component",
};

// 渲染函数同时接收 args 和 context
export const Default = (args, context) => {
  // 把全局选中的 typeSelector 合并到组件参数中
  const mergedArgs = {
    ...args,
    type: context.globals.typeSelector,
  };
  return MyComponent(mergedArgs);
};

Default.args = {
  title: "Some title defined on component level"
};

这样每次工具栏切换类型时,context.globals.typeSelector会自动同步最新值,渲染函数会把它传给Twig模板,你写的{% if type === "a" %}条件渲染就能正常工作了。

方案二:用装饰器全局注入(适合全项目组件都需要的场景)

如果你的很多组件都需要这个全局类型参数,不想每个故事都重复写合并逻辑,可以在全局装饰器里统一处理,把全局类型自动注入到所有故事的args中。修改你的.preview.js:

export const globalTypes = {
  typeSelector: {
    title: "Type",
    defaultValue: "a",
    toolbar: {
      dynamicTitle: true,
      items: [{value: "a", title: "Type A"},{value: "b", title: "Type B"}]
    }
  }
};

export const decorators = [
  (storyFn, context) => {
    // 合并全局类型到当前故事的参数中
    const updatedArgs = {
      ...context.args,
      type: context.globals.typeSelector,
    };
    // 用更新后的参数渲染故事
    const storyContent = storyFn({ ...context, args: updatedArgs });
    // 保留原来的wrapper类逻辑
    return `<div class="type-${context.globals.typeSelector}">${storyContent}</div>`;
  },
];

这样所有故事的args都会自动带上type参数,你的MyComponent.stories.js完全不用修改,保持原来的写法就行:

import MyComponent from "./MyComponent.twig";

export default {
  title: "Components/My Component",
};

export const Default = (args) => MyComponent(args);

Default.args = {
  title: "Some title defined on component level"
};

为什么不用事件监听的方式?

你之前尝试的GLOBALS_UPDATED事件监听其实绕远路了,而且手动触发UPDATE_STORY_ARGS可能会引发不必要的状态同步问题。上面两种方案都是利用Storybook本身的上下文传递机制,更简洁也更符合官方推荐的用法。

备注:内容来源于stack exchange,提问作者KimWexler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 11:09:34