Storybook配置argType的select控件后切换侧边栏视图defaultValue丢失
问题修复方案
根因说明
Storybook 6及以上版本中,argTypes字段下定义的defaultValue属于过时的配置方式,仅在组件首次加载时生效,路由切换(侧边栏跳转其他组件再返回)时会被全局状态重置,这是官方已明确的非预期配置导致的问题。
同时你当前的配置存在冗余冲突:control下重复定义了values,和上层的options、mapping属性作用重复,会加剧配置解析的异常概率。
修复代码
const themes = { defaultTheme, salesTheme, cuttingTheme, } as const; export default { title: 'atoms/Button', component: Button, // 全局默认值统一放在顶层args字段,这是官方推荐的标准写法 args: { theme: themes.defaultTheme }, argTypes: { theme: { options: Object.keys(themes), mapping: Object.values(themes), control: { type: 'select', labels: Object.keys(themes) // 移除冗余的values配置,和上层options/mapping重复 }, // 移除argTypes下的defaultValue配置 }, }, } as ComponentMeta<typeof Button>;
可选补充:单Story独立默认值配置
如果不同的Story需要配置不同的theme默认值,可以在对应Story的args字段单独声明,优先级高于全局默认值:
// 示例:销售主题专属Story export const SalesButton: ComponentStory<typeof Button> = (args) => <Button {...args} /> SalesButton.args = { theme: themes.salesTheme }
内容的提问来源于stack exchange,提问作者dagda1
相关产品推荐
相关产品推荐

