组件或元素的正确PropType是什么

时间:2017-02-19 10:24:36

标签: reactjs

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

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失败:值componentClass的道具div无效   提供给Col

3 个答案:

答案 0 :(得分:1)

您的组件未定义componentClass属性 - 您的道具称为containerElement,您应该使用oneOfType

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

答案 1 :(得分:0)

试试这个:

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

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

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

答案 2 :(得分:0)

现在发布了道具类型 15.7.0 的您可以:

Col.propTypes = {
  ...
  containerElement: PropTypes.elementType,
}
相关问题