React 无状态组件的 TypeScript 返回类型是什么?



这里的返回类型是什么?

const Foo
: () => // ???
= () => (
<div>
Foobar
</div>
)

本答案中提到的StatelessComponent类型已被弃用,因为在引入 Hooks API 后,它们并不总是无状态的。

函数组件的类型为React.FunctionComponent,它有一个别名React.FC以保持简洁。

它有一个必需的属性,一个函数,它将返回一个ReactElementnull。它有一些可选的属性,如propTypescontextTypesdefaultPropsdisplayName

下面是一个示例:

const MyFunctionComponent: React.FC = (): ReactElement => {
return <div>Hello, I am a function component</div>
}

以下是 @types/react 16.8.24 中的类型:

type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
interface ISomeCoolInterface {
some: 'string';
cool: 'string';
props: 'string' 
}    
const SomeCoolComponent
: React.FC<ISomeCoolInterface> 
= ({ some, cool, props }): JSX.Element => {
return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>      
}

这里重要的一点是返回类型JSX.Element

这里正确的返回类型是ReactElement<P>,但更好的选择是使用这样的React.StatelessComponent<P>

const Foo
: React.StatelessComponent<{}>
= () => (
<div>
Foobar
</div>
)

如果使用function关键字,则最佳返回类型似乎是JSX.Element | null

目前,我们的团队使用 JSXNode 作为速记,因为只有这两种类型可以直接作为 JSX 结果返回:

type JSXNode = JSX.Element | null;

编辑:看起来最终React.ReactNode是JSX的预期返回类型,但目前是不可能的。 (参考资料)

<小时 />

背景:

这里似乎没有一个答案可以解决最常见的现代情况 - 你有一个返回元素的函数。这应该返回什么类型?

function MyComponent(): SomeTypeHere {
return <>...</>;
}

隐藏组件的建议方法是返回 null,因此不清楚这将是什么干净返回类型。键入 JSX。元素 |到处都是 null,甚至像这样制作自定义类型似乎没有必要,因为这种情况的普遍性。ReactNode 也不起作用,因为 undefined 不能作为 JSX 返回。

总体而言,最佳返回类型似乎是JSX.Element | null。 这是不使用function关键字时使用的FC类型的返回类型:

const MyComponent: FC = () => { <>...</> }

我还要添加.SFC,它代表无状态功能组件。

const Foo
: React.SFC<{}>
= () => (
<div>
Foobar
</div>
)

请参阅 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts

每个JSX元素都只是用于调用React.createElement(component,props,...儿童)。

function createElement<P extends DOMAttributes<T>, T extends Element>(
type: string,
props?: ClassAttributes<T> & P,
...children: ReactNode[]): DOMElement<P, T>;

所以它DOMElement<P, T>

或者对于传统函数,也许这个???

import { ReactElement } from "react";
export default function Home () : ReactElement<React.FC> {
return (
<>
Hello world
</>
)
}

最新更新