reactjs - 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?
解决方案
在 Github 上引用React-Typescript 备忘单
您还可以使用
React.FunctionComponent
(或简写React.FC
)编写组件:
const App: React.FC<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
与“正常功能”版本的一些区别:
- 它为静态属性提供类型检查和自动完成功能,如
displayName
,propTypes
和defaultProps
-但是,目前使用defaultProps
with 存在已知问题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
语法稍微冗长一些,并没有提供明显的优势,因此优先考虑“普通函数”语法。
推荐阅读
- python - Locust 将请求和响应正文导出到 csv 文件
- javascript - 为什么我来自 BehivourSubject 的消息会重复每条新收到的消息?
- visual-studio-code - 为 vs 代码启用和禁用 Python 扩展没有效果
- javascript - 未捕获(承诺)错误:上传后控制台中的文件堆栈选择器初始化错误
- windows-10 - L如何将新的图标覆盖链接到我的应用程序?
- laravel - Laravel 验证 ID 是否具有关系实例
- java - Java 10 copyOf 工厂方法是否适合构造函数中的防御性副本
- android - 夜间模式不会更新启动画面的颜色
- swift - 在 macOS 10.15.7 (19H1030) 上渲染 CIImage 会导致空白图像
- spring-data-jpa - 通过spring批处理从数据库中读取并从数据库中删除