React PropTypes: range of numbers

前端 未结 4 1296
自闭症患者
自闭症患者 2021-02-14 21:56

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) 
         


        
4条回答
  •  遥遥无期
    2021-02-14 22:49

    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
    }
    

提交回复
热议问题