React proptype array with shape

前端 未结 6 1151
感情败类
感情败类 2020-12-12 15:11

Is there a built-in way to use proptypes to ensure that an array of objects being passed to a component is actually an array of objects of a specific shape?

Maybe so

6条回答
  •  天涯浪人
    2020-12-12 15:44

    This was my solution to protect against an empty array as well:

    import React, { Component } from 'react';
    import { arrayOf, shape, string, number } from 'prop-types';
    
    ReactComponent.propTypes = {
      arrayWithShape: (props, propName, componentName) => {
        const arrayWithShape = props[propName]
        PropTypes.checkPropTypes({ arrayWithShape:
            arrayOf(
              shape({
                color: string.isRequired,
                fontSize: number.isRequired,
              }).isRequired
          ).isRequired
        }, {arrayWithShape}, 'prop', componentName);
        if(arrayWithShape.length < 1){
          return new Error(`${propName} is empty`)
        }
      }
    }
    

提交回复
热议问题