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

使用HOC包裹组件后Storybook Controls消失的问题求助

解决HOC包裹后Storybook Controls消失的问题

问题根源在于:HOC(高阶组件)会对原始组件进行包装,导致Storybook无法自动识别包装后组件的Props类型,进而无法生成Controls面板。下面是几个可行的解决办法:


办法一:手动配置argTypes

在Story的Meta配置里手动声明组件的Props信息,强制Storybook生成Controls。修改你的index.stories.tsx:

import { Meta } from '@storybook/react'
import Avatar from '../Avatar'
import { AvatarProps } from '../Avatar.types' // 导入Props类型
export { AvatarColor } from './AvatarColor.stories'
export { Default } from './AvatarDefault.stories'

export default {
  title: 'Components/Avatar',
  component: Avatar,
  parameters: {
    docs: {
      description: {
        component: `An Avatar is a graphical representation of a user, team, or entity.
        Avatar can display an image, icon, or initials, and supports various sizes and shapes.`,
      },
    },
  },
  decorators: [
    (Story) => (
      <div
        style={{
          display: 'flex',
          gap: '5px',
          flexWrap: 'wrap',
        }}
      >
        <Story />
      </div>
    ),
  ],
  // 手动配置argTypes
  argTypes: {
    size: {
      control: 'number',
      defaultValue: 50,
      description: 'The Size.'
    },
    someotherprop: {
      control: 'number',
      defaultValue: 80,
      description: 'The prop.'
    },
    color: {
      control: 'text',
      defaultValue: 'red',
      description: 'The color.'
    },
    // 按需添加HTMLAttributes里的常用属性
    className: { control: 'text' },
    style: { control: 'object' }
  }
} as Meta<AvatarProps> // 明确指定Meta的Props类型

办法二:优化HOC的类型定义

让你的withAlign HOC保留原始组件的Props类型,这样Storybook就能自动识别。修改HOC的类型声明:

import React, { ComponentType } from 'react';

// 用泛型保留原始组件的Props类型
function withAlign<T extends {}>(Component: ComponentType<T>): ComponentType<T> {
  return function AlignedComponent(props: T) {
    // 这里是你的HOC逻辑
    return <Component {...props} />;
  };
}

// 导出时使用这个泛型HOC包装组件
export default withAlign(Avatar);

这样包装后的组件会完整保留AvatarProps的类型信息,Storybook就能自动生成Controls面板。


办法三:在Story中明确传递Props类型

修改你的AvatarDefault.stories.tsx,用Storybook的ComponentStory类型绑定Props:

import { ComponentStory } from '@storybook/react';
import Avatar from '../Avatar';
import { AvatarProps } from '../Avatar.types';

// 明确指定Story的Props类型
export const Default: ComponentStory<typeof Avatar> = (props) => (
  <Avatar {...props}>Yooo</Avatar>
);

// 可以在这里设置默认参数
Default.args = {
  size: 50,
  someotherprop: 80,
  color: 'red'
};

同时在index.stories.tsx的Meta里指定组件类型:

export default {
  title: 'Components/Avatar',
  component: Avatar, // 这里的Avatar是withAlign包装后的组件
  // ...其他配置
} as Meta<typeof Avatar>;

内容的提问来源于stack exchange,提问作者PEPEGA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:18:34