如何在 React 中验证 Prop 的 class 和它的字段(嵌套对象)的 class?

How to validate the class of a Prop and class of it's field (nested object) in React?

我有一个 class 这样的:

class ResponseState() {
   constructor(data) {
      this.data = data;
   }
}

现在我可以验证道具是这种类型的:

Container.propTypes = {
   myProp: PropTypes.instanceOf(ResponseState).isRequired,
};

这工作正常,但我如何验证 myProp.data 的类型呢?如果我使用 PropTypes.shape,那么我无法检查 myProp 本身。

有一个类似的问题 here,但它并没有给出这个确切问题的答案。

我很惊讶没有看到 PropTypes 的任何组合形式。

您可以使用自定义验证器:

Container.propTypes = {
   myProp: function(props, propName, componentName) {
      if (!propName in props) {
         return new Error(propName + " is required");
      }
      const value = props[propName];
      if (!(value instanceof ResponseState)) {
         return new Error(propName + " must be an instance of ResponseState");
      }
      if (/*...validate value.data here ...*/) {
         return new Error(propName + " must have etc. etc.");
      }
   }
};