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

ukxgm1gy  于 5个月前  发布在  React
关注(0)|答案(8)|浏览(75)

这里的返回类型会是什么?

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

字符串

mklgxw1f

mklgxw1f1#

this answer中提到的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;
}

5lwkijsr

5lwkijsr2#

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

wfypjpf4

wfypjpf43#

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

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

字符串

6pp0gazn

6pp0gazn4#

如果使用function关键字,最佳返回类型似乎是JSX.Element | null
现在我们的团队使用JSXNode作为简写,因为这是唯一两种可以直接作为JSX结果返回的类型:
type JSXNode = JSX.Element | null;
编辑:看起来最终会是React。ReactNode是JSX的预期返回类型,但目前还不可能。(Reference

背景:

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

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

字符串
隐藏该组件的推荐方法是返回null,因此不清楚该返回类型是什么。|null无处不在,甚至像这样定制一个自定义类型似乎是不必要的,因为这种情况是多么普遍。ReactNode也不工作,因为undefined不能作为JSX返回。
总的来说,最好的返回类型似乎是JSX.Element | null。这是FC类型的返回类型,如果你没有使用function关键字:

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

wmvff8tz

wmvff8tz5#

参见https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts
每个JSX元素只是调用React. js元素(组件, prop ,.子元素)的语法糖。

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

字符串
所以是DOMElement<P, T>

s4chpxco

s4chpxco6#

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

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

字符串

nkhmeac6

nkhmeac67#

或者是传统的功能,也许是这个?

import { ReactElement } from "react";

export default function Home () : ReactElement<React.FC> {
    return (
        <>
            Hello world
        </>
    )
}

字符串

pdtvr36n

pdtvr36n8#

import "./App.css";

function App(): React.ReactElement {
  return <>hello</>;
}

export default App;

字符串
在react函数组件中使用它。

相关问题