使 children 需要一个 PropType,但在 parent?

Make a PropType required for children but specify this on the parent?

我有一个 Parent 组件,它可以有不同的 children。 Children 在 Parent 之内时必须有一个 hash 道具,但如果他们在 Parent 之外则没有。

<Parent>
  // Many different components can go here
  <Something hash="#one" />
  <SomethingElse hash="#one" />
</Parent>

<App>
  <Something />
  <SomethingElse />
</App>

我可以为 Parent 定义任何 children 必须具有 hash 属性的 PropTypes 吗?

您可以为可以放置动态逻辑的 propType 定义自定义验证器。

示例代码来自 official documentation :

// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
  if (!/matchme/.test(props[propName])) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
},