React.PropTypes array with specific length

后端 未结 4 1487
一向
一向 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:51

    A custom function would be the correct approach here.

      const propTypes = {
        TWO_NUMBERS: arrayOfLength.bind(null, 2)
      }
    
      const arrayOfLength = (expectedLength, props, propName, componentName) => {
        const arrayPropLength = props[propName].length
    
        if (arrayPropLength !== expectedLength) {
          return new Error(
            `Invalid array length ${arrayPropLength} (expected ${expectedLength}) for prop ${propName} supplied to ${componentName}. Validation failed.`
          )
        }
      }
    

提交回复
热议问题