为什么我不能在React中使用HOC? [英] Why can't I use an HOC in React here?
问题描述
我有这个HOC,为了清楚起见,我省略了代码:
const TestWrapper =(Component)=> {
return function(){
return< Component />
}
}
这样被称为:
const b =<面包屑项目= {面包屑} />
const ConnectedAppHeader = TestWrapper(b);
返回(
< div>
< ConnectedAppHeader />
< / div>
)
我有一个名为 Breadcrumbs
的组件,它需要一个道具。如果我只将它与<面包屑items = {面包屑} />
一起使用,则运行正常。但是,一旦我尝试将其包装在 TestWrapper
中,就会出现此错误:
React.createElement:类型无效-预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。
我的渲染类型显然有误,但我被卡住了。我如何使此HOC起作用?
HOC希望将组件函数作为参数-不是组件功能的实际 instance 。当您应该通过 the 面包屑
面包屑元素>函数/类本身。这是因为您要在 TestWrapper
中创建一个新元素-您不能从一个元素中创建一个元素,而必须从实际的类或函数中创建一个元素。 / p>
例如,您可以将包装程序修改为:
const TestWrapper =(Component,items)=> {
return function(){
return< Component items = {items} />
}
}
然后像这样使用它:
const ConnectedAppHeader = TestWrapper(面包屑,面包屑);
I have this HOC, I've omitted code for clarity:
const TestWrapper = (Component) => {
return function() {
return <Component />
}
}
Which is called like this:
const b = <Breadcrumbs items={ crumbs } />
const ConnectedAppHeader = TestWrapper(b);
return (
<div>
<ConnectedAppHeader />
</div>
)
I have a component named Breadcrumbs
which takes a prop. This runs OK if I just use it with <Breadcrumbs items={ crumbs } />
. But as soon as I try to wrap it in the TestWrapper
I get this error:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
I've obviously got my rendering type wrong, but I'm stuck. How do I get this HOC working?
HOCs expect component functions as arguments -- not an actual instance of the component function. You're trying to pass a Breadcrumbs
element when you're supposed to pass the Breadcrumbs
function/class itself. That's because you're creating a new element in TestWrapper
-- you can't an element from an element, you have to create an element from the actual class or function.
For example, you could modify the wrapper to become this:
const TestWrapper = (Component, items) => {
return function() {
return <Component items={items} />
}
}
Then use it like so:
const ConnectedAppHeader = TestWrapper(Breadcrumbs, crumbs);
这篇关于为什么我不能在React中使用HOC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!