防止 div as children in PropTypes only allow one component

Preventing div as children in PropTypes only allow one component

我有一个组件可以克隆子组件并将一些新道具传递给它。 在我的 PropTypes 中,我只想允许 React 组件而不是其他任何东西。 例如:

<PartentComponent>
  <ChildContent/>
</PartentComponent>

它并不总是被称为 ChildContent,它可以是组件的任何名称。

我不希望 parentComponent 允许除组件之外的任何内容。 这是不允许的。

<PartentComponent>
  <div>content</div>
</PartentComponent>

我尝试在我的 ParentComponent 中使用元素的 PropType。但仍然接受 div

Modal.propTypes = {
  children: PropTypes.element,
};

除了组件之外我什么都不想要的原因是我在 cloneElement 中传递了无法在 div 上使用的道具。

  const childComponent = React.Children.map(children, child =>
    cloneElement(child, {
      end: onEndProcesss,
    }));

{React.Children.only(this.props.children)}

验证 children 只有一个 child(一个 React 元素)并且 returns 它。否则此方法会引发错误。

import React from 'react'

function Modal() {
  return(
    {React.Children.only(this.props.children)}
  )

}

Modal.propTypes = {
  children: PropTypes.element,
};

你不能用 "native" PropTypes API 来做到这一点。 但是您可以创建自己的验证器。您可以从 react.element 的 type 属性 解包组件类型。 https://github.com/facebook/react/blob/master/packages/react/src/ReactElement.js#L118

如果 typeof element.type 是字符串你需要抛出错误

您可以在此处找到 proptypes 类型检查器示例:https://www.ian-thomas.net/custom-proptype-validation-with-react/