React.PropTypes.number float with min and max

扶醉桌前 提交于 2019-12-22 08:37:51

问题


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



回答4:


I know this is an old post, but I thought I would share as I ran into this issue as well. All of the other answers address how to use this functionality for a single prop, but if you need this for multiple props, then creating a reusable PropType might be a better solution.

// Allow min/max values to be passed to PropType validator
export default const numberBetween = (min, max) => {
    // Return CustomProp to be executed
    return (props, propName, componentName) => {
        const prop = props[propName];
        if(typeof prop !== 'number' || prop < min || prop > max) {
            return new Error(`Prop ${propName} must be a number between ${min} and ${max} on ${componentName}`);
        }
    }
}

It is then used like this:

completed: numberBetween(1, 10)

Hope this helps someone!



来源:https://stackoverflow.com/questions/41821181/react-proptypes-number-float-with-min-and-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!