Storybook出现‘Element type is invalid’错误的排查及对应TypeScript版本实现指导
Storybook出现‘Element type is invalid’错误的排查及对应TypeScript版本实现指导
我完全理解遇到这个错误的头疼之处,咱们先一步步梳理可能的问题点,再给你适配好TypeScript版本的Storybook写法。
错误排查步骤
这个错误大概率是组件导入导出不匹配或者依赖问题导致的,你可以按下面的顺序检查:
核对组件的导出与导入方式
先确认../src/Typography里的MyTypography是默认导出还是命名导出:- 如果组件是
export default MyTypography,那你现在的import MyTypography from '../src/Typography'是对的; - 如果是
export const MyTypography,则需要改成import { MyTypography } from '../src/Typography'。
另外注意你描述里的拼写错误(componetn),不过看你代码里是正确的component={MyTypography},这部分没问题。
- 如果组件是
验证依赖包的正确性
确保@emotion/react已经正确安装,并且ThemeProvider确实是从这个包导出的——可以去你的node_modules/@emotion/react里确认下导出结构,或者重新安装依赖试试:npm install @emotion/react --save检查Storybook版本兼容性
确认@storybook/blocks的版本和你项目里的Storybook核心版本一致,版本不匹配很容易导致某些Block组件变成undefined。你可以查看package.json里的相关依赖,比如@storybook/react、@storybook/blocks的版本号是否统一。MDX语法与组件使用校验
检查你的MDX文件里所有Storybook组件(Meta、Story、Preview等)的标签是否正确闭合,参数是否传递正确——比如Meta的component属性必须指向一个有效的React组件,不能是undefined。
TypeScript版本的Storybook实现
基于你提供的JavaScript代码,我给你适配了TypeScript版本,同时补充了类型定义来保证类型安全:
import { Meta, Story, ArgsTable, Preview } from '@storybook/blocks'; import { ThemeProvider } from '@emotion/react'; import MyTypography from '../src/Typography'; import customTheme from '../src/themes/customTheme'; // 导入MyTypography的Props类型,假设你在Typography.tsx里已经定义了 import type { MyTypographyProps } from '../src/Typography'; // 定义Story的Args类型,和组件Props对齐 type MyTypographyStoryArgs = MyTypographyProps; <Meta title="MyTypography" component={MyTypography} parameters={{ layout: "centered" }} tags={['autodocs']} /> # MyTypography The `MyTypography` component renders typography elements with various styles. You can customize the variant and children to render different typography elements. ## Variants ### Example Usage <Preview> <Story<MyTypographyStoryArgs> name="Default Typography" args={{ variant: "h1", children: "Hello World", }} > {({ args }) => ( <ThemeProvider theme={customTheme}> <MyTypography variant={args.variant}>{args.children}</MyTypography> </ThemeProvider> )} </Story> </Preview> ### Different Variants <Preview> <Story<MyTypographyStoryArgs> name="All Typography Variants" args={{ children: "Typography Example", }} > {({ args }) => ( <ThemeProvider theme={customTheme}> {["h1", "h2", "h3", "h4", "h5", "h6"].map((variant) => ( <MyTypography key={variant} variant={variant}> {`${variant.toUpperCase()}: ${args.children}`} </MyTypography> ))} </ThemeProvider> )} </Story> </Preview> ## Props <ArgsTable of={MyTypography} />
需要注意的是:
- 确保你在
../src/Typography.tsx里已经定义了MyTypographyProps类型,比如:
export type MyTypographyProps = { variant: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; children: React.ReactNode; // 其他你需要的属性 }; export default function MyTypography({ variant, children }: MyTypographyProps) { // 组件实现 }
- TypeScript版本的Story里,我们给
Story组件加上了泛型<MyTypographyStoryArgs>,这样args的类型会和组件Props严格对齐,避免类型错误。
备注:内容来源于stack exchange,提问作者Anand Deep Singh
相关产品推荐
相关产品推荐

