在创建HOC时,我不确定会包装哪种组件,有时它是另一个React组件,有时它可能是一个普通的DOM元素,如li
和a
。
WrappedComp = myHOC(BaseComponent)
MyHOC会将额外的道具传递给包装的组件,在大多数情况下,这将按其应有的方式工作。
但有时,当BaseComponent是li
时,它不会接受额外的道具,React会抛出一个警告Unkown Prop Warning
,说明DOM元素不接受非标准的dom属性:https://facebook.github.io/react/warnings/unknown-prop.html
那么如何检查BaseComponent是DOM元素还是其他元素呢?如果是的话,我不会把额外的道具传给它。
有没有更好的方法来做这件事?
发布于 2017-04-12 20:44:22
检查BaseComponent
是否为React组件,并添加所需的道具。
if(BaseComponent.prototype.isReactComponent){
//add props
}
发布于 2021-06-22 17:11:13
简短回答:
检查元素是否为string
类型,以检查元素是否为DOM元素。
检查元素是否为function
类型,以检查元素是否为React组件。
示例:
if (typeof BaseComponent.type === 'string') {
return BaseComponent
}
// add props
长篇答案:
正如在the React documentation中定义的,像<li>
或<span>
这样的内置组件会导致字符串'li'
或'span'
被传递给React.createElement
,例如React.createElement("li")
。
以大写字母开头的类型(如<Foo />
)将编译为React.createElement(Foo)
,并与JavaScript文件中定义或导入的组件相对应。
因此,React组件的类型为function
,而DOM组件的类型为string
。
下面的WrapperComponent
记录每个子元素的typeof child.type
。输出为function
,string
,string
。
function WrappedComponent({children}) {
return React.Children.map(children, child => {
console.log(typeof child.type)
...
})
}
const BaseComponent = ({children}) => children
function App() {
return (
<WrappedComponent>
<BaseComponent>This element has type of function</BaseComponent>
<span>This element has type of string</span>
<li>This element has type of string</li>
</WrappedComponent>
)
}
https://stackoverflow.com/questions/43366843
复制相似问题