是否有一种内置的方法来使用原型来确保传递给组件的对象数组实际上是特定形状的对象数组?

也许像这样?

annotationRanges: PropTypes.array(PropTypes.shape({
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
})),

我是不是漏了什么特别明显的东西?看来这个会很抢手。


它就在那儿……就在我眼皮底下

来自react文档本身:https://facebook.github.io/react/docs/reusable-components.html

// An array of a certain type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

你可以使用React.PropTypes.shape()作为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,
}

请参阅文档的道具验证部分。

更新

从react v15.5开始,使用react。PropTypes已弃用,应该使用独立包prop-types:

// 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,
}

这里有一个ES6速记导入,你可以参考。更易于阅读和输入。

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

是的,您需要使用PropTypes。arrayOf而不是PropTypes。数组,你可以这样做:

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  annotationRanges: PropTypes.arrayOf(
    PropTypes.shape({
      start: PropTypes.string.isRequired,
      end: PropTypes.number.isRequired
    }).isRequired
  ).isRequired
}

有关原型的更多详细信息,请访问这里的“使用proptypes进行类型检查”

如果我要为一个特定形状多次定义相同的原型,我喜欢将其抽象到一个原型文件中,这样如果对象的形状发生了变化,我只需要更改一个地方的代码。它有助于使代码库干涸一点。

例子:

// 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)
}

这是我的解决方案,以防止一个空数组:

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`)
    }
  }
}