简体   繁体   中英

React, when to use propTypes

When developing in house components that will fail fast without the required props, I feel that the prop requirement check is performed in testing and the added weight of the propTypes should be excluded from the production code. I'm talking about components that take no user input and have static props.

Example:

const Button = ({ label, onClick }) => (
    <button type="button" onClick={ onClick }>{ label }</button>
);

Seems to me that propTypes would be extraneous runtime code for components like this.

Using prop-types is a best practice, but no one forces you too use them. So if it is a personal project and you don't feel the need for prop-types, no one will blame you.

But when you work on a project with multiple people, or a library/npm-package, always use prop-types. Your button may not require a lot of props now, but you never know what functionality you will need in the future. As soon as you realize your component is growing and you will need to implement prop-types retrospectively, you'll regret not using prop-types.

So: If you work with a group or on a library ALWAYS use prop-types. If not, it's up to you, but keep in mind that having to implement prop-types a while after you have written a component can be a real pain in the ass.

Seems to me that propTypes would be extraneous runtime code for components like this.

For production code it is, that's why I recommend the following babel plugin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM