【问题标题】:Preventing div as children in PropTypes only allow one component在 PropTypes 中防止 div 作为子级只允许一个组件
【发布时间】:2020-01-09 07:33:40
【问题描述】:

我有一个组件可以克隆孩子并将一些新的道具传递给它。 在我的 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,
    }));

【问题讨论】:

  • 您可以通过为“propTypes”对象中的键提供函数来添加自定义道具类型。

标签: reactjs react-proptypes


【解决方案1】:

您无法使用“本机”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/

【讨论】:

    【解决方案2】:

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

    验证 children 只有一个子元素(一个 React 元素)并返回它。否则这个方法会报错。

    import React from 'react'
    
    function Modal() {
      return(
        {React.Children.only(this.props.children)}
      )
    
    }
    
    Modal.propTypes = {
      children: PropTypes.element,
    };
    
    

    【讨论】:

    • 感谢 wootsbot 但这仍然允许
      content
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多