我想定义组件的类型。不管它接收了多少个道具,它是一个类还是一个函数组件,我甚至不在乎它是否返回一个JSX元素,或者只是null或任何字符串。
我想说的是"一个组件",它被React定义为任何可能有一个key prop和一个ref prop的东西。我尝试使用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.ComponentType
,其类型为:
React.ComponentClass<P, any> | React.FunctionComponent<P>
的例子:
function Ramadan(){
return <></>
}
const templatesMap: { [key: string]: React.ComponentType<any> } = {
ramadan: Ramadan,
adha: () => <></>,
fitir: React.forwardRef((props, ref) => <></>),
unset: class MyClassComp extends React.Component {
render() { return <></> }
},
mothers: () => null,
birthDay: () => <></>,
}
游乐场