React PropTypes:数字范围 [英] React PropTypes: range of numbers

查看:178
本文介绍了React PropTypes:数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数字在某个范围内,是否有更好的方法来验证

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

避免写

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


推荐答案

根据文档,您可以定义customProps

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
}

这篇关于React PropTypes:数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆