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,
}