React.PropTypes.number float with min and max

2019-05-07 18:07发布

问题:

completed: React.PropTypes.number,

Can i specify a minimum and maximum to a number props in React component.

expected something like following:

completed: React.PropTypes.numberBetween(min, max),

I generate an array to specify the range

attempt:

completed: React.PropTypes.oneOf(Array.from({length: max -min+1, (v, k) => k + min})),

However , i want completed props to accept also float as well , whereas , it accepts only integer now .

How to make the following constraints combined :

  • prop is number ( integer, float, double,...any number)

  • between MIN and MAX

回答1:

You can use Custom Validation.

completed: function(props, propName, componentName) {
   if(props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid');
   }
}


回答2:

By writing a Custom Props Validator, u can achieve this. try this:

num: function(props, propName, componentName) {
    if(typeof props[propName] != 'number'){
      return new Error ('Invalid type of `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }else if (props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }
},


回答3:

The CustomProp just like the Docs said:

completed: (props, propName, componentName) => 
             (props[propName] < MIN || props[propName] > MAX) && new Error('Invalid');