是否有使用 proptypes 的内置方法来确保传递给组件的对象数组实际上是特定形状的对象数组?
也许是这样的?
annotationRanges: PropTypes.array(PropTypes.shape({
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
})),
我在这里错过了一些非常明显的东西吗?看来这会很受追捧。
是否有使用 proptypes 的内置方法来确保传递给组件的对象数组实际上是特定形状的对象数组?
也许是这样的?
annotationRanges: PropTypes.array(PropTypes.shape({
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
})),
我在这里错过了一些非常明显的东西吗?看来这会很受追捧。
您可以将其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,
}
请参阅文档的Prop Validation部分。
更新
截至react v15.5, usingReact.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,
}
是的,您需要在代码中使用PropTypes.arrayOf而不是PropTypes.array,您可以执行以下操作:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
  annotationRanges: PropTypes.arrayOf(
    PropTypes.shape({
      start: PropTypes.string.isRequired,
      end: PropTypes.number.isRequired
    }).isRequired
  ).isRequired
}
此外如需详细了解proptypes,访问类型检查有了PropTypes 这里
它就在……就在我的鼻子底下:
从react文档本身:https : //facebook.github.io/react/docs/reusable-components.html
// An array of a certain type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
有一个 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: [],
  }
}
如果我要为一个特定的形状多次定义相同的 proptype,我喜欢将它抽象到一个 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)
}