React 中的 PropTypes [英] PropTypes in React

查看:63
本文介绍了React 中的 PropTypes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些例子中,我看到过这样的事情:

In some examples, I have seen something like this:

Footer.propTypes = {
  completedCount: PropTypes.number.isRequired,
  activeCount: PropTypes.number.isRequired,
  filter: PropTypes.string.isRequired,
  onClearCompleted: PropTypes.func.isRequired,
  onShow: PropTypes.func.isRequired
}

这些 PropTypes 到底在做什么?它们是值得拥有还是必须拥有?

What are these PropTypes really doing? Are they nice-to-have or must-have?

推荐答案

正如 finalFreq 所指出的,我站纠正!所提供的示例在 React 的未来版本中可以完美运行.React 不推荐直接调用 proptypes 函数,但注释组件在当前和未来版本中都可以正常工作."

As pointed out by finalFreq I stand corrected! "the example provided will work perfectly fine in future versions of react. React deprecated calling the proptypes function directly but annotating a component will work just fine in current and future versions."

如果你只是在 JS 中学习类型,我建议使用 flowtypes,它在构建时而不是运行时工作.这在编辑器中有效!编辑器扩展还使用强推理来在不那么明显的类型丢失、空值或不同类型时提醒您.主要好处是它可以在不减慢运行时间的情况下加快开发速度并减少错误.您可以在生产之前轻松地从 js 中剥离流程.

I suggest flowtypes if you are just learning types in JS, works at build time instead of run-time. This works in the editor! The editor extensions also use strong inference to alert you when a less obvious type is missing, null, or of a different type. The main benefit is that it speeds up development and reduces bugs without slowing run-time. You can easily strip the flow from your js before production.

FlowType: https://flowtype.org/docs/getting-started.html#_

如果您想要更强大和功能更强大的集合,我建议使用 TypeScript,以学习 JS 中的类型.

I suggest TypeScript if you are wanting the more powerful and featureful set, to learn types in JS.

TypeScript: https://github.com/Microsoft/TypeScript

为了回答您的问题,proptypes 从来都不是必须的,并且一度被认为是实验性的.我喜欢它们,但恕我直言,flowtype 更实用.主要用途是通过在开发早期发出警告来防止滥用组件,并提供编码文档以便更好地理解(后代).

To answer your question proptypes were never a must have and were at one point considered experimental. I loved them, but flowtype is more pragmatic IMHO.The main use is to prevent the misuse of a component by warning early on in development and offer coded documentation for better understanding(posterity).

我还想清楚,proptypes 也可以被剥离以进行生产.

I also want to be clear that proptypes can be stripped for production also.

这篇关于React 中的 PropTypes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆