我遇到了一个我无法解决的问题。对于一个项目,我们使用 React 使用以下代码(简化)从 JSON 输入生成布局:
function generateComponents(children, params) {
let comps = [];
if (!children || children && children.length === 0) {
return [];
}
forEach(children, (comp) => {
let compName = comp.component;
let createdComp;
switch (compName) {
case 'test1':
createdComp = TestOne(Object.assign({}, comp, params));
break;
case 'test2':
createdComp = TestTwo(Object.assign({}, comp, params));
break;
}
comps.push(createdComp)
}
}
return comps.length === 1 ? comps[0] : comps;
}
这很好用并且布局生成正确。我们想更进一步,将 createdComp
包装在 Higher Order Component
中。我们通过以下方式实现了这一点:
function generateComponents(children, params) {
// see above for implementation
let component;
if (condition)
component = testingHOC(createdComp);
else
component = createdComp
comps.push(component);
}
// TestingHOC.js
export function testingHoc(WrappedComponent) {
console.log('wrapped')
return class TestingHoc extends Component {
render() {
console.log('props TestingHOC', this.props);
return ( <WrappedComponent { ...this.props} />);
}
}
};
这破坏了我们的组件生成。该代码不返回任何内容。唯一被记录的是 console.log('wrapped')
,永远不会调用类的渲染函数。我们在这里缺少什么?
编辑: 渲染类的渲染方法:
render() {
const children = this.state.children;
const {params} = this.props;
const arrChildren = isArray(children) ? children : [children];
let comps = generateComponents(arrChildren, params || {});
if (isArray(comps)) {
return (
<ViewComponent>
{comps}
</ViewComponent>
);
} else {
return comps;
}
}
编辑 2:
Console.log of {comps}
with the testingHoc
{comps}
的 Console.log 没有 testingHoc
编辑 3
添加了 ViewComponent 的代码:
import React from 'react';
const ViewComponent = (props) => (
<div {...props}/>
);
export default ViewComponent;
最佳答案
您面临的问题是因为 React element and a React component. 之间的内在差异
当您不使用 HOC 时,您正在创建一个可以通过第一个 console.log 图像看到的 React 元素。这是 reconciliation 之后的输出发生了。
当您使用 HOC 时,您的 HOC 会返回一个组件,该组件在您的第二个 console.log 图像中显示为 test(props)
函数。
要与您的 HOC 增强组件具有相同的功能,您需要将 generateComponents
函数中的代码更改为
if (condition){
let Comp = testingHOC(createdComp);
component = <Comp/>;
}
关于javascript - React HOC 类不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093750/