gpt4 book ai didi

reactjs - 为什么 React.FunctionComponenent 优于传统的函数定义?

转载 作者:行者123 更新时间:2023-12-04 12:14:22 26 4
gpt4 key购买 nike

我一直将 React 组件(使用 typescript )定义为:

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

在网上我看到很多这样的例子:
const MyComponent: React.FC = (props: PropsType) => {
//...
}

我知道它们几乎相同,但是 Typescript 社区中的首选约定是什么?

最佳答案

报价React-Typescript Cheatsheet在 Github 上

You can also write components with React.FunctionComponent (or the shorthand React.FC):


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

Some differences from the "normal function" version:

  • It provides typechecking and autocomplete for static properties like displayName, propTypes, and defaultProps - However, there are currently known issues using defaultProps with React.FunctionComponent. See this issue for details
  • It provides an implicit definition of children (see below) - however there are some issues with the implicit children type (e.g. DefinitelyTyped#33006), and it might considered better style to be explicit about components that consume children, anyway.

const Title: React.FunctionComponent<{ title: string }> = ({  
children, title }) => <div title={title}>{children}</div>;

  • In the future, it may automatically mark props as readonly, though that's a moot point if the props object is destructured in the constructor.

  • React.FunctionComponent is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).

In most cases it makes very little difference which syntax is used, but the React.FC syntax is slightly more verbose without providing clear advantage, so precedence was given to the "normal function" syntax.

关于reactjs - 为什么 React.FunctionComponenent 优于传统的函数定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com