React proptype array with shape

前端 未结 6 1156
感情败类
感情败类 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:59

    If I am to define the same proptypes for a particular shape multiple times, I like abstract it out to a proptypes file so that if the shape of the object changes, I only have to change the code in one place. It helps dry up the codebase a bit.

    Example:

    // Inside my proptypes.js file
    import PT from 'prop-types';
    
    export const product = {
      id: PT.number.isRequired,
      title: PT.string.isRequired,
      sku: PT.string.isRequired,
      description: PT.string.isRequired,
    };
    
    
    // Inside my component file
    import PT from 'prop-types';
    import { product } from './proptypes;
    
    
    List.propTypes = {
      productList: PT.arrayOf(product)
    }
    

提交回复
热议问题