【问题标题】:Typing return type of React components输入 React 组件的返回类型
【发布时间】:2020-06-05 15:38:50
【问题描述】:

This PR 到 Create-React-App 删除 React.FC 作为组件的返回类型(原因请参阅 PR)。这是否意味着 ESlint 的 explicit function return type 规则不再适用于 React 组件?如果是这样,如何让 ESlint 满意?

【问题讨论】:

  • 你遇到什么问题了吗?

标签: reactjs typescript eslint


【解决方案1】:

您可以使用React.ReactElement | null 作为函数组件的返回类型。这就是 React.FC 今天所做的。

interface Props {
  children: React.ReactNode;
}

const MyComponent = ({ children }: Props): React.ReactElement => (
  <div>{children}</div>
)

【讨论】:

  • ReactNode 还包括undefined,这是不允许的。返回 undefined 会导致 React 抛出 Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null。
【解决方案2】:

一种选择是将您的函数声明为 ComponentType,它封装了返回类型:

import { ComponentType } from 'react';

const App: ComponentType<AppProps> = () => (
  <div>Whatever</div>
);

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2021-01-05
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多