【发布时间】:2020-06-05 15:38:50
【问题描述】:
This PR 到 Create-React-App 删除 React.FC 作为组件的返回类型(原因请参阅 PR)。这是否意味着 ESlint 的 explicit function return type 规则不再适用于 React 组件?如果是这样,如何让 ESlint 满意?
【问题讨论】:
-
你遇到什么问题了吗?
标签: reactjs typescript eslint
This PR 到 Create-React-App 删除 React.FC 作为组件的返回类型(原因请参阅 PR)。这是否意味着 ESlint 的 explicit function return type 规则不再适用于 React 组件?如果是这样,如何让 ESlint 满意?
【问题讨论】:
标签: reactjs typescript eslint
您可以使用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。
一种选择是将您的函数声明为 ComponentType,它封装了返回类型:
import { ComponentType } from 'react';
const App: ComponentType<AppProps> = () => (
<div>Whatever</div>
);
【讨论】: