React:检测变量的 PropTypes

React: Detect a variable's PropTypes

在 React 组件中,如果我声明:

MyComponent.propTypes = {
  // An object that could be one of many types
  header: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
  ]),
}

如何知道 header 在我的 render 方法中是字符串还是数字?

在您的 render 方法中,您可以使用 typeof 运算符来确定 header 变量的类型。如果你有像 Lodash 这样的东西,你也可以使用它的实用方法之一(_.isString, _.isNumber,等等)。

注意:您的评论 "An object that could be one..." 可能应该重述为 "A variable that could be one...",因为您说的不是对象而是字符串或数字。

实际上,如果值的类型是基本类型之一(字符串、数字...),您可以使用@jrubins 的上述方法。

自定义React组件,必须勾选关联字段.type。这是演示代码:

Steps.propTypes = {
  // must not be an empty array of Step
  children: PropTypes.arrayOf(function(props, propName) {
    const value = props[propName];
    if ( value.type !== Step) {
      return new Error('Must supply an instance of Step');
    }
  }),
};