React proptype array with shape

前端 未结 6 1188
感情败类
感情败类 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 16:08

    You can use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf():

    // an array of a particular shape.
    ReactComponent.propTypes = {
       arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
         color: React.PropTypes.string.isRequired,
         fontSize: React.PropTypes.number.isRequired,
       })).isRequired,
    }
    

    See the Prop Validation section of the documentation.

    UPDATE

    As of react v15.5, using React.PropTypes is deprecated and the standalone package prop-types should be used instead :

    // an array of a particular shape.
    import PropTypes from 'prop-types'; // ES6 
    var PropTypes = require('prop-types'); // ES5 with npm
    ReactComponent.propTypes = {
       arrayWithShape: PropTypes.arrayOf(PropTypes.shape({
         color: PropTypes.string.isRequired,
         fontSize: PropTypes.number.isRequired,
       })).isRequired,
    }
    

提交回复
热议问题