Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - PropTypes in React

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
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."

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#_

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

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

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...