加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React自定义PropTypes

发布时间:2020-12-15 07:25:07 所属栏目:百科 来源:网络整理
导读:http://stackoverflow.com/ques... // You can also specify a custom validator. It should return an Error// object if the validation fails. Don't `console.warn` or throw,as this// won't work inside `oneOfType`.customProp: function(props,propN

http://stackoverflow.com/ques...

// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw,as this
// won't work inside `oneOfType`.
customProp: function(props,propName,componentName) {
  if (!/matchme/.test(props[propName])) {
    return new Error('Validation failed!');
  }
}

How type checkers work

function(props,componentName,location,propFullName) => null | Error

PropTypes.number({ myProp: 'bad' },'myProp');
// => [Error: Invalid undefined `myProp` of type `string` supplied
//     to `<<anonymous>>`,expected `number`.]

PropTypes.number({ myProp: 'bad' },'myProp','MyComponent','prop')
// => [Error: Invalid prop `myProp` of type `string` supplied
//     to `MyComponent`,expected `number`.]


const minMaxPropType = (props,...rest) => {
  const error = PropTypes.number(props,...rest);
  if (error !== null) {
    return error;
  }

  if (props.min >= props.max) {
    const errorMsg = (propName === 'min') ? 'min should be less than max' : 'max should be greater than min';
    return new Error(errorMsg);
  }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读