Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 组件或元素的正确类型是什么_Reactjs - Fatal编程技术网

Reactjs 组件或元素的正确类型是什么

Reactjs 组件或元素的正确类型是什么,reactjs,Reactjs,我正在创建一个我希望元素类型可配置的组件 const Col = ({ containerElement, children }) => { return ( <containerElement> {children} </containerElement> ); }; Col.defaultProps = { containerElement: 'div' }; 但它不能正确验证 警告:失败的属性类型:无效的属性值div

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

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

Col.defaultProps = {
  containerElement: 'div'
};
但它不能正确验证

警告:失败的属性类型:无效的属性值
div
提供给


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

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

Col.propTypes = {
    className: PropTypes.string,
    containerElement: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
    ]),
}
因为React组件是全局意义上的函数

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

现在,随着道具类型15.7.0的发布,您可以执行以下操作:

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

虽然这是正确的,但我认为这不会解决验证问题。这是我的错误。如果名称正确,它仍然无法通过验证。您到底要向组件传递什么?如果该值实际上是一个元素,则无论如何不能将其用作
React.createElement('containerElement',…)
的语法糖。即使是字符串,
'containerElement'
也将传递给
React.createElement
,而不是变量
containerElement
。在担心验证错误之前,我会确保代码本身产生正确的结果(即正确工作)。同意@FelixKling。您需要通过类似于
const ContainerElement=ContainerElement.inner
的方式实例化。请参阅此问题:此元素与
元素
❓元素表示实例(
),元素类型表示组件类(
Foo
)。
typeof (class MyClass {}) // => "function"
Col.propTypes = {
  ...
  containerElement: PropTypes.elementType,
}