【问题标题】:What is the correct PropTypes for component or element组件或元素的正确 PropType 是什么
【发布时间】:2017-07-08 15:23:56
【问题描述】:

我正在创建一个我希望元素类型可配置的组件。

const Col = ({ containerElement, children }) => {
  return (
    <containerElement>
      {children}
    </containerElement>
  );
};

Col.defaultProps = {
  containerElement: 'div'
};

所以容器元素可以是上面 defaultProps 中的元素,也可以是一个组件。

<Col containerElement={<MyComponent} />

我无法让propTypes 进行验证,我已经尝试过:

Col.propTypes = {
  className: PropTypes.string,
  containerElement: PropTypes.oneOf([
    PropTypes.string,
    PropTypes.element
  ]),

但它没有正确验证。

警告:失败的 propType:无效的 prop componentClass 的值 div 提供给Col

【问题讨论】:

  • 你传递给组件的到底是什么?如果该值确实是一个元素,那么无论如何您都不能将其用作&lt;containerElement&gt;&lt;containerElement&gt;React.createElement('containerElement', ...) 的语法糖。即使是字符串,'containerElement' 也会传递给React.createElement,而不是变量 containerElement。在担心验证错误之前,我会确保代码本身产生正确的结果(即正常工作)。
  • 同意@FelixKling。您需要通过const ContainerElement = containerElement.inner 之类的方式实例化 。看到这个问题:stackoverflow.com/a/39655113/504018

标签: reactjs


【解决方案1】:

现在随着 prop-types 15.7.0 的发布,您可以:

Col.propTypes = {
  ...
  containerElement: PropTypes.elementType,
}

【讨论】:

  • 这和element有什么区别@❓
  • element 用于实例 (&lt;Foo /&gt;),elementType 用于组件类 (Foo)。
【解决方案2】:

您的组件上没有定义 componentClass 属性 - 您的属性称为 containerElement,您应该使用 oneOfType

Col.propTypes = {
  className: PropTypes.string,
  containerElement: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element
  ])

【讨论】:

  • 虽然这是正确的,但我认为这不会解决验证问题。
  • 那是我的错字。使用正确的名称,它仍然无法通过验证。
【解决方案3】:

试试这个:

Col.propTypes = {
    className: PropTypes.string,
    containerElement: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
    ]),
}

因为 React 组件是全局意义上的函数,并且

typeof (class MyClass {}) // => "function"

【讨论】:

    猜你喜欢
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2013-04-04
    • 2020-02-20
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多