如何有条件地展示Storybook全局argTypes?
Storybook 6 全局argTypes冗余属性条目解决方案
全局配置theme、size这类通用属性的argTypes后,不包含对应prop的组件属性表出现冗余条目的核心原因是:全局argTypes不会自动和单个组件的实际props做匹配校验,默认全量注入到所有story的属性表配置中。不需要删除已有的全局argTypes配置,通过以下两种方案即可实现冗余条目的彻底隐藏:
方案1:全局自动过滤(推荐,零业务侵入)
一次配置后所有story自动生效,不需要给单个组件写额外配置:
- 保留
.storybook/preview.js中已经写好的全局argTypes公共配置,不需要做任何删减 - 新增全局装饰器,在渲染前自动匹配当前组件的实际props列表,把全局配置中组件不存在的prop直接从属性表和控件栏移除
参考配置代码:
// .storybook/preview.js // 原有全局公共argTypes配置保持不变 const globalCommonArgTypes = { theme: { control: { type: 'select' }, options: ['light', 'dark'], description: '组件主题样式', table: { defaultValue: { summary: 'light' } } }, size: { control: { type: 'radio' }, options: ['small', 'middle', 'large'], description: '组件尺寸规格', table: { defaultValue: { summary: 'middle' } } } } // 原有全局parameters配置保持不变 export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } } } // 新增全局过滤装饰器 export const decorators = [ (Story, context) => { const currentComponent = context.component // 多框架兼容:收集当前组件实际声明的所有props const validProps = new Set([ ...Object.keys(currentComponent.propTypes || {}), // React JSX 组件propTypes ...Object.keys(currentComponent.props || {}), // Vue2/React class组件props ...Object.keys(currentComponent.__docgenInfo?.props || {}), // TS类型解析生成的props ...Object.keys(currentComponent.__props || {}) // Vue3 组件props ]) // 遍历全局配置,隐藏组件不存在的prop Object.keys(globalCommonArgTypes).forEach(propKey => { if (!validProps.has(propKey)) { context.argTypes[propKey] = { table: { disable: true }, // 彻底从props属性表移除条目 control: false // 同步移除控件栏对应控件,双保险 } } }) return Story() } ] // 正常导出全局argTypes export const argTypes = globalCommonArgTypes
这个方案适配React、Vue等Storybook支持的主流框架,只要根据自己用的框架调整validProps的收集逻辑即可,后续新增组件、新增story都不需要重复处理通用prop配置。
方案2:单story局部覆盖(适合特殊组件补漏)
如果个别组件存在props命名特殊、定制化需求高的情况,可以直接在对应组件的story配置里,单独把不需要的全局prop配置为隐藏即可,不会影响其他组件的全局配置:
// 例如某组件不支持size属性,在其story文件中配置 export default { title: 'Business/SomeSpecialComponent', component: SomeSpecialComponent, argTypes: { size: { table: { disable: true }, control: false } } }
配置注意事项
- 使用TypeScript的React项目,需要确保
react-docgen-typescript插件正常启用,否则__docgenInfo字段无法正确读取TS声明的props,会出现漏判 - 不要只配置
control: false,这个配置只会隐藏控件,不会移除属性表中的条目,必须搭配table: { disable: true }才能实现属性表的彻底隐藏 - 如果项目里有高阶组件包裹的情况,需要在装饰器里取到原始组件再做props匹配,避免高阶组件的props干扰判断
内容的提问来源于stack exchange,提问作者jared_hexagon
相关产品推荐
相关产品推荐

