[英]React.PropTypes.number float with min and max
completed: React.PropTypes.number,
Can i specify a minimum and maximum to a number props
in React component. 我可以在React组件中为数字props
指定最小值和最大值。
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 . 但是,我希望completed
道具也接受浮动,而现在它只接受整数。
How to make the following constraints combined : 如何将以下约束组合在一起:
prop
is number ( integer, float, double,...any number) prop
是数字(整数,浮点数,双数,......任意数字)
between MIN and MAX 在MIN和MAX之间
You can use Custom Validation. 您可以使用自定义验证。
completed: function(props, propName, componentName) {
if(props[propName] < MIN || props[propName] > MAX) {
return new Error('Invalid');
}
}
By writing a Custom Props Validator
, u can achieve this. 通过编写Custom Props Validator
,您可以实现此目的。 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.');
}
},
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. 所有其他答案都解决了如何将此功能用于单个道具,但如果您需要多个道具,那么创建可重复使用的PropType可能是更好的解决方案。
// 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! 希望这有助于某人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.