简体   繁体   English

如何使用具有defaultProps的propTypes验证道具?

[英]How to validate props with propTypes having defaultProps?

Earlier when we were not using defaultProps, we use to get warning in the console that this props is not passed. 较早时,当我们不使用defaultProps时,我们用于在控制台中获得警告,指出该props没有通过。 But after configuring the props signature using defaultProps we don't get any errors as such. 但是在使用defaultProps配置了props签名之后,我们不会得到任何错误。 So, how to configure both to work as expected? 那么,如何配置两者以使其按预期工作呢?

/* Default Props */
MyApp.defaultProps = {
  data: {
    totalCount: 123
  },
  name: 'john doe'
};

/* Proptypes */
MyApp.proptypes = {
  data: {
    totalCount: Proptypes.number.isRequired
  },
  name: Proptypes.string.isRequired
};
import PropTypes from 'prop-types';

You must use 您必须使用

class test { 
    static propTypes = { 
        optionalBool: PropTypes.bool,
        requiredProperty: PropTypes.number.isRequired
}}

You are already doing it correctly, the problem you had before is that when the component was initialized, it had null values for its props, so you get run time warning expecting some null value props, default props sets that value even on initial component mount. 您已经正确地执行了此操作,以前的问题是组件被初始化时,其props具有空值,因此您会收到运行时警告,期望某些空值props,即使在初始组件安装时,默认props也会设置该值。 :) :)

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

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