Storybook装饰器里的参数为什么没生效?

嘉木 阅读 53

我在用Vue Storybook给按钮组件加一个主题装饰器,想通过参数切换主题样式,但发现传递的参数完全没反应…

写了个装饰器函数:


export const withTheme = (storyFn, { theme }) => {
  return (
    
{storyFn()}
); };

然后在按钮的故事里这样写:


export default {
  title: 'Atoms/Button',
  decorators: [
    (story) => withTheme(story, { theme: 'lightblue' })
  ]
};

结果背景色根本没变,控制台也没报错,明明参数传递方式参考了官方文档啊,哪里出问题了?

我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
小涵舒
小涵舒 Lv1
问题出在装饰器函数的参数解构上,Storybook 的上下文对象结构不是你写的那样。改成这样就行:

export const withTheme = (storyFn, context) => {
const theme = context.parameters.theme;
return (

{storyFn()}

);
};

另外确保在预览配置里加了参数支持,.storybook/preview.js 加上这行:

export const parameters = {
theme: 'lightblue'
};

搞定。
点赞 4
2026-02-15 17:19
博主瑞珺
问题在于你写的 withTheme 装饰器没正确嵌套故事内容,同时也没应用主题样式。直接改成这样:

export const withTheme = (storyFn, context) => {
const { theme } = context.parameters;
return (
<div style={{ backgroundColor: theme, padding: '20px' }}>
{storyFn()}
</div>
);
};

export default {
title: 'Atoms/Button',
decorators: [withTheme],
parameters: { theme: 'lightblue' }
};


记得把参数加到 parameters 里,装饰器自动读取。
点赞 17
2026-01-29 16:19