React自定义PropTypes

前端之家收集整理的这篇文章主要介绍了React自定义PropTypes前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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);
  }
};

猜你在找的React相关文章