React PropTypes: range of numbers

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 12:08:32

问题


Is there a better way to validate if a number is inside a range?

Avoiding to write

PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 

回答1:


According to the documentation, you can define your customProps

customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  }

So for your case you can try the following

function withinTen(props, propName, componentName) {
  componentName = comopnentName || 'ANONYMOUS';

  if (props[propName]) {
    let value = props[propName];
    if (typeof value === 'number') {
        return (value >= 1 && value <= 10) ? null : new Error(propName + ' in ' + componentName + " is not within 1 to 10");
    }
  }

  // assume all ok
  return null;
}


something.propTypes = {
  number: withinTen,
  content: React.PropTypes.node.isRequired
}



回答2:


You can use custom Prop validator.

completed: function(props, propName, componentName) {
    if (props[propName]>=1 &&  props[propName]<=10) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  }

Please refer the documentation for further details.

https://reactjs.org/docs/typechecking-with-proptypes.html




回答3:


If it's a sequence, You can use a smart ES6. :)

[BTW, I believe the first answer is the most appreciate, this one is just trick]

PropTypes.oneOf(...[...(new Array(10))].map((_, i) => i + 1))

Explanation: This [...(new Array(10))].map((_, i) => i + 1) part will give to the sequence.

// Sequence
console.log([...(new Array(5))].map((_, i) => i + 1))

// Spreading the Sequence numbers 
console.log(...[...(new Array(5))].map((_, i) => i + 1))


来源:https://stackoverflow.com/questions/50489434/react-proptypes-range-of-numbers

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