如何为React Storybook不同目录的故事设置不同根容器类?
解决方案
有两种简单的方式可以实现给不同目录的Storybook故事设置不同根类的需求:
方案一:全局装饰器根据故事路径动态切换类名
修改项目根目录下的preview.js,利用装饰器的context参数判断当前故事所属目录,动态选择容器类:
export const decorators = [ (Story, context) => { // 通过故事的title判断是否属于新组件目录(title对应故事文件的路径结构) const isNewComponent = context.title.includes('mpg-component-new'); const containerClass = isNewComponent ? 'mpg-component-new-container' : 'mpg-component-container'; return ( <div className={containerClass}> <Story /> </div> ); }, ];
context.title的值对应你在故事文件里定义的title字段(比如新组件按钮的故事可能会写title: 'mpg-component-new/Button'),通过includes就能精准区分新旧组件的故事。
方案二:给新组件目录单独配置preview.js
在mpg-component-new目录下创建专属的preview.js文件,直接定义该目录下故事的装饰器:
// mpg-component-new/preview.js export const decorators = [ (Story) => ( <div className="mpg-component-new-container"> <Story /> </div> ), ];
Storybook会自动优先使用目录级的preview.js配置,所以这个目录下的所有故事都会应用新的容器类,而mpg-component目录下的故事依然使用根目录preview.js里的原有装饰器。
注意事项
- 确保你的CSS文件里已经定义了
mpg-component-new-container对应的样式规则 - 如果使用TypeScript,
context参数的类型可以引用import type { StoryContext } from '@storybook/react';
内容的提问来源于stack exchange,提问作者TirupathiRao
相关产品推荐
相关产品推荐

