繁体   English   中英

是否可以在不使用箭头函数的情况下使用 TypeScript 键入 React 函数组件?

[英]Is it possible to type a React function component with TypeScript without using arrow functions?

目前我将这个 React 组件输入如下:

import React, { FunctionComponent } from "react";

const HelloWorld : FunctionComponent = () => {
  return (
    <div>
      Hello
    </div>
  );
}

export default HelloWorld;

我不想使用箭头函数并像这样编写我的组件:

import React, { FunctionComponent } from "react";

function HelloWorld() {
  return (
    <div>
      Hello
    </div>
  );
}

export default HelloWorld;

是否可以将普通函数输入为FunctionComponent

FunctionComponent类型基本上归结为一个接收 props 并返回一个ReactElement

(props: PropsWithChildren<P>, context?: any): ReactElement | null;

因此,一种选择是相应地键入您的非箭头函数:

function HelloWorld(): ReactElement {
  return (
    <div>
      Hello
    </div>
  );
}

另一种选择(与 TS React 生态系统的其余部分更好地集成)是将您的函数存储在一个命名变量中:

interface SomeProps {
  someValue: number
}

const HelloWorld: FunctionComponent<SomeProps> = function HelloWorld({ someValue }) {
  return <div>Hi {someValue}</div>
}

总的来说,我建议您只使用箭头函数,因为它们提供了好处,尤其是在涉及 JS 范围和this引用时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM