问题如下,我有一家工厂:
import React from 'react';
export default (componentFactory) =>
{
return Component =>
{
class Factory extends React.Component
{
render()
{
let { state, props } = this;
return componentFactory({ state, props }, Component);
}
}
return Factory;
};
}
然后是一个简单的页面组件包装器:
import React from 'react';
const Page = ({children, appState}) =>
(
<section>
{React.cloneElement(children, {appState})}
</section>
);
export default Page;
因此,为了创建一个HomePage,我同样使用HomeFactory:
import React from 'react';
import Factory from '../Factory';
import HeroBanner from '../Banner/HeroBanner';
const HomeFactory = ({state, props}, HomePage) =>
{
return <HomePage {...props} {...state} >
<HeroBanner />
</HomePage>;
};
export default Factory(HomeFactory);
正在安装的HomePage组件的最终代码如下:
import React from 'react';
import Page from '../Page';
import HomeFactory from '../HomeFactory';
const HomePage = ({children, appState}) =>
{
return (
<Page appState={appState}>
{children}
</Page>
);
};
export default HomeFactory(HomePage);
问题似乎是HomeFactory组件,我把它放在:
return <HomePage {...props} {...state} >
<HeroBanner />
</HomePage>;
按照给出的示例,这是100%正确工作,但是,当我尝试将多个组件放在数组的形式或只是嵌套的许多组件时,如:
return <HomePage {...props} {...state} >
<HeroBanner />
<HeroBanner />
<HeroBanner />
</HomePage>;
我收到以下错误:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
基本上,页面包装器组件获取作为其父组件HomePage的子项传入的属性,这些属性取自工厂方法。
问题是JSX隐含发生了什么,我无法做到以下几点?
答案 0 :(得分:1)
在您的Page组件中,当您传递多个子项时,您需要使用cloneElement
和Children.map
(this.props.children
是一个特殊的类似数组的对象)
请参阅此答案:stackoverflow.com/a/38011851/3794660了解更多详情。