Reactjs TypeScript中的React组件类型
在TypeScript中描述react组件类型的正确方法是什么? 假设我们有一个返回react组件的函数。 职能:Reactjs TypeScript中的React组件类型,reactjs,typescript,Reactjs,Typescript,在TypeScript中描述react组件类型的正确方法是什么? 假设我们有一个返回react组件的函数。 职能: const getTabContent: () => ReactElement = () => { switch (tab) { case 1: return <Images images={images} onSelect={onSelect}/>; default: return <Search onSe
const getTabContent: () => ReactElement = () => {
switch (tab) {
case 1:
return <Images images={images} onSelect={onSelect}/>;
default:
return <Search onSelect={onSelect}/>;
}
};
const getTabContent:()=>ReactElement=()=>{
开关(选项卡){
案例1:
返回;
违约:
返回;
}
};
在这里,我将返回类型描述为ReactElement,但我想知道它是否正确,或者我应该将其描述为ReactComponentElement,甚至完全不同?
另外,这两种类型都是泛型,如果其中一种是正确的,如何完整地描述它们
UPD ReactElement似乎适合这里,因为,例如,FC(FunctionComponent)返回它功能组件的正确类型是
React.FunctionComponent
或React.FC
,这是它的快捷别名
import React, { FC } from 'react';
const getTabContent: FC = () => {
switch (tab) {
case 1:
return <Images images={images} onSelect={onSelect}/>;
default:
return <Search onSelect={onSelect}/>;
}
};
FC
是一种通用类型,因此您可以向组件“添加”道具:
interface SomeComponentProps {
foo: string;
}
const SomeComponent: FC<SomeComponentProps> = ({ children, foo }) => (
<div className={`Hello ${foo}`}>{children}</div>
);
interface-SomeComponentProps{
foo:string;
}
常量SomeComponent:FC=({children,foo})=>(
{儿童}
);
如果要将FunctionComponent与类组件一起使用,
然后使用
React.ComponentType
类型脚本具有强大的类型推断功能。只要在大多数地方使用它。只有顶级组件需要细粒度的接口
const getTabContent=({tab,onSelect}:{tab:number,onSelect:(ev:React.SyntheticEvent)=>void}=>{
开关(选项卡){
案例1:
返回;
违约:
返回;
}
};
您确定
是功能组件吗?它不是,getTabContent
是
是所述功能组件的返回值Thank you@3Dos。但如果我重写图像并搜索类组件,我应该在这里和提到这些组件的任何地方更改类型?我想你不明白。这里的函数组件是getTabContent
,只要它返回JSX值或null,就可以了。事实上,这里不需要FC类型,因为类型推断就足够了。虽然FC
类型允许您使用children
道具,但一些开发人员喜欢总是使用FC键入,因此每个组件都已键入。我不知道它是否在较新版本中被更改,但是全名是React.FunctionComponent
,而不是React.FunctionComponent
React.Component
?谢谢@MoshFeu,但它不合适。编译器被搞糊涂了
interface SomeComponentProps {
foo: string;
}
const SomeComponent: FC<SomeComponentProps> = ({ children, foo }) => (
<div className={`Hello ${foo}`}>{children}</div>
);
const getTabContent = ({ tab, onSelect }: { tab: number, onSelect: (ev: React.SyntheticEvent) => void }) => {
switch (tab) {
case 1:
return <Image src="123"/>;
default:
return <Search onSelect={onSelect}/>;
}
};