如何在TypeScript中定义自定义React组件类型并解决赋值错误?
React组件Title的TypeScript类型错误解决
我有一个React组件Title,它会根据传入的props渲染h1至h6、span或div标签。
正常运行场景
以下写法没有TypeScript错误:
interface ComponentProps { tag?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "span" | "div"; type: "title" | "subtitle"; text: string; variation: string; } const Title: React.FC<ComponentProps> = ({tag}) => { let Tag = tag; return ( <Tag>Text</Tag> ) }
错误场景
当尝试给Tag赋值默认值时出现TypeScript错误。需求是检查tag属性是否为空,若为空则根据type属性赋值h1或h2:
const Title: React.FC<ComponentProps> = ({tag, type, text, variation}) => { let Tag = tag || ''; if(!Tag.length){ if(type=='title'){ Tag = 'h1' } else { Tag = 'h2' } } return ( <Tag className={variation}>{text}</Tag> ) }
错误信息
Type '{ children: string; className: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'children' does not exist on type 'IntrinsicAttributes'
注意:不能使用React.createElement。
解决方法
错误原因
代码中let Tag = tag || ''将Tag的类型推断为宽泛的string,而非限定的HTML标签类型集合。TypeScript仅允许在JSX中使用已知的HTML元素标签类型,因此传递children和className时会触发类型错误。
修正方案1:使用空值合并运算符直接初始化
const Title: React.FC<ComponentProps> = ({ tag, type, text, variation }) => { // 直接根据tag是否存在设置默认值,确保类型始终为有效标签 const Tag = tag ?? (type === 'title' ? 'h1' : 'h2'); return ( <Tag className={variation}>{text}</Tag> ); };
修正方案2:显式指定Tag的类型
const Title: React.FC<ComponentProps> = ({ tag, type, text, variation }) => { // 显式声明Tag的类型为合法标签集合 let Tag: ComponentProps['tag'] | 'h1' | 'h2'; if (tag) { Tag = tag; } else { Tag = type === 'title' ? 'h1' : 'h2'; } return ( <Tag className={variation}>{text}</Tag> ); };
两种方案都能确保Tag的类型始终是限定的HTML标签类型,避免TypeScript类型推断错误。
内容的提问来源于stack exchange,提问作者user12551649
相关产品推荐
相关产品推荐

