React.PropTypes array with specific length

后端 未结 4 1499
一向
一向 2021-02-19 22:05

Is it possible to use React.PropTypes to enforce length\'s on an array?

Here is a very simple case:

const TWO_NUMBERS = PropTypes.array; // i          


        
4条回答
  •  自闭症患者
    2021-02-19 22:56

    Inspired by the answer of @finalfreq, I came up with this. It handles two numbers (floats in this case) and can also be used as arrayOf(twoNumbers). Not sure how to make it work like twoNumbers.isRequired yet...

    Also I think the code is cleaner and easier to follow if you don't use the negation in the validation comparison.

    import invariant from 'invariant';
    
    function isValid(value) {
      return Array.isArray(value) && value.length === 2 && value.every(Number.isFinite);
    }
    
    export default function twoNumbers(props, propName, componentName) {
      if (Array.isArray(props)) {
        props.forEach((item, index) => {
          invariant(
            isValid(item),
            `Array item index ${index} is ${item}, but needs to be an array of two numbers`
          );
        });
      }
    
      const value = props[propName];
    
      if (!value) return; // not required so could be null
    
      invariant(isValid(value), `${componentName} ${propName} needs to be an array of two numbers`);
    }
    

提交回复
热议问题