React中任意类型组件的TypeScript类型定义该如何选择?
问题:如何定义任意React组件的TypeScript类型?
我想要定义一种组件类型,无论它接收多少props,是类组件还是函数组件,甚至不管它返回JSX元素、null还是任意字符串都可以。我只想表示“一个组件”——也就是React定义的可能包含key属性和ref属性的任意内容。
我尝试使用React.Component:
function Ramadan(){ return <></> } const templatesMap: { [key: string]: React.Component } = { ramadan: Ramadan, adha: () => <></>, fitir: () => <></>, unset: () => <></>, mothers: () => <></>, birthDay: () => <></>, }
但TypeScript报错:
Type '() => Element' is not assignable to type 'Component<{}, {}, any>'.ts(2322)
WriteContent.tsx(10, 25): The expected type comes from this index signature.
我想知道这种任意组件的正确类型是什么?
解决方案
你用错类型了——React.Component是类组件实例的类型,不是组件本身的构造函数/函数组件类型,所以函数组件肯定没法赋值给它。
要表示任意类组件或函数组件,不管props和返回值,正确的类型是React.ComponentType<any>:
ComponentType是React内置的类型别名,它涵盖了ComponentClass(类组件构造函数)和FunctionComponent(函数组件)两种类型- 泛型参数
any表示允许组件接收任意props,完全符合你“不管接收多少props”的需求
修改后的代码示例:
import React from 'react'; function Ramadan(){ return <></> } // 也支持类组件 class EidAdha extends React.Component { render() { return <div>Eid Adha</div>; } } const templatesMap: { [key: string]: React.ComponentType<any> } = { ramadan: Ramadan, adha: EidAdha, fitir: () => <></>, unset: () => null, // 支持返回null mothers: () => 'Happy Mothers Day', // 支持返回字符串 birthDay: () => <div>Birthday</div>, }
如果你的场景还需要包含原生HTML元素(比如把'div'当作组件值),可以用更宽泛的React.ElementType,它包含了ComponentType和所有HTML标签名的字符串类型。
内容的提问来源于stack exchange,提问作者Islam Y-
相关产品推荐
相关产品推荐

