简体   繁体   English

React,何时使用propTypes

[英]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. 当开发内部组件在没有所需道具的情况下快速失败时,我觉得支柱要求检查是在测试中执行的,并且propTypes的附加权重应该从生产代码中排除。 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. 在我看来,propTypes将是这样的组件的无关运行时代码。

Using prop-types is a best practice, but no one forces you too use them. 使用prop-types是一种最佳实践,但没有人强迫你使用它们。 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. 但是,当您处理具有多个人的项目或库/ npm-package时,请始终使用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. 一旦你意识到你的组件正在增长并且你需要回顾性地实现prop-types,你会后悔没有使用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. 在我看来,propTypes将是这样的组件的无关运行时代码。

For production code it is, that's why I recommend the following babel plugin . 对于生产代码,这就是我推荐以下babel插件的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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