React 无状态组件的 TypeScript 返回类型是什么? [英] What is the TypeScript return type of a React stateless component?

查看:51
本文介绍了React 无状态组件的 TypeScript 返回类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的返回类型是什么?

const Foo: () =>//???= () =>(<div>食品吧

)

解决方案

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

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

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

这是一个例子:

const MyFunctionComponent: React.FC = (): ReactElement =>{return <div>你好,我是一个函数组件</div>}

这里是来自@types/react 16.8.24 的类型:

type FC

=功能组件<P>;interface FunctionComponent

{(props: PropsWithChildren<P>, context?: any): ReactElement |空值;propTypes?: WeakValidationMap

;contextTypes?: ValidationMap;defaultProps?: Partial<P>;显示名称?:字符串;}

What would the return type be here?

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

解决方案

StatelessComponent type mentioned in this answer has been deprecated because after introducing the Hooks API they are not always stateless.

A function component is of type React.FunctionComponent and it has an alias React.FC to keep things nice and short.

It has one required property, a function, which will return a ReactElement or null. It has a few optional properties, such as propTypes, contextTypes, defaultProps and displayName.

Here's an example:

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

And here are the types from @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;
}

这篇关于React 无状态组件的 TypeScript 返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆