首页 > 解决方案 > Why is React.FunctionComponenent preferred over conventional function definitions?

问题描述

I've always defined React components (with typescript) as:

function MyComponent(props: PropsType): React.ReactElement | null {
    //...
}

Online I see a lot of examples like:

const MyComponent: React.FC = (props: PropsType) => {
    //...
}

I understand they are pretty much the same, but what is the preferred convention in the Typescript community?

标签: reactjstypescript

解决方案


在 Github 上引用React-Typescript 备忘单

您还可以使用React.FunctionComponent(或简写React.FC)编写组件:

const App: React.FC<{ message: string }> = ({ message }) => (  
  <div>{message}</div>
); 

与“正常功能”版本的一些区别:

  • 它为静态属性提供类型检查和自动完成功能,如displayName,propTypesdefaultProps-但是,目前使用defaultPropswith 存在已知问题React.FunctionComponent。有关详细信息,请参阅此问题
  • 它提供了children(见下文)的隐式定义 - 但是隐式类型存在一些问题children(例如 , DefiniteTyped#33006),无论如何,它可能认为更好的样式是明确的组件消耗children
const Title: React.FunctionComponent<{ title: string }> = ({  
children, title }) => <div title={title}>{children}</div>;
  • 将来,它可能会自动将 props 标记为readonly,尽管如果 props 对象在构造函数中被解构,那将是一个有争议的问题。

  • React.FunctionComponent是明确的返回类型,而普通函数版本是隐式的(或者需要额外的注释)。

在大多数情况下,使用哪种语法几乎没有什么区别,但是React.FC语法稍微冗长一些,并没有提供明显的优势,因此优先考虑“普通函数”语法。


推荐阅读