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

dag*_*da1 4 reactjs

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

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

Col.defaultProps = {
  containerElement: 'div'
};
Run Code Online (Sandbox Code Playgroud)

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

<Col containerElement={<MyComponent} />
Run Code Online (Sandbox Code Playgroud)

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

Col.propTypes = {
  className: PropTypes.string,
  containerElement: PropTypes.oneOf([
    PropTypes.string,
    PropTypes.element
  ]),
Run Code Online (Sandbox Code Playgroud)

但它无法正确验证。

警告:失败的 propType:提供给componentClass的值无效,divCol

Ela*_*evy 7

现在,随着 prop-types 15.7.0发布,您可以执行以下操作:

Col.propTypes = {
  ...
  containerElement: PropTypes.elementType,
}
Run Code Online (Sandbox Code Playgroud)

  • element 用于实例 (`&lt;Foo /&gt;`),elementType 用于组件类 (`Foo`)。 (3认同)