React Hoc函数返回类



函数作为React子类无效。如果你从渲染返回一个组件而不是<Component />,可能会发生这种情况。或者你想调用这个函数而不是返回它。

import './App.css';
import React, { Component } from 'react';
const OOO = () => {
//console.log(this.props.children)
return class extends Component {
render() {
return (
<Rem {...this.props} />
);
}
}
}
class Rem extends Component {
render() {
return (
<p>Helo</p>
)
}
}
export default OOO;

如果您从渲染返回组件而不是<Component />,则可能发生这种情况

这正是你在这里所做的。调用<OOO />返回class而不是JSX元素。

这不是一个真正的高阶组件,因为您没有将内部组件Rem作为参数。你打算这么做吗?它看起来像这样:

const withOOO = (InnerComponent) => {
return class extends Component {
render() {
return (
<InnerComponent {...this.props} />
);
}
}
}
class Rem extends Component { ... }
export default withOOO(Rem);

如果这只是一个使用Rem的组件,而不是HOC,那么您不需要创建新类。

const OOO = (props) => {
return <Rem {...props} />;
};
class Rem extends Component { ... }
export default OOO;

我认为你使用了错误的函数,函数OOO返回一个类,这个类你可以使用。我不知道你为什么要这样做,但这里是如何使用HOC:

//your code in a file called OOO.js
import React, { Component } from 'react';
const OOO = () => {
//you cannot log this.props here, it is not in the class
//console.log(this.props.children)
//I think you have to name the class but I'm not sure
//Have not used classes in React for quite some time
//even React documentation lists a large amount of
//disadvantages using classes and it's only around for
//legacy code
return class MyComponent extends Component {
render() {
//here you can log this.props
//console.log(this.props.children)
return <Rem {...this.props} />;
}
};
};
class Rem extends Component {
render() {
return <p>Helo</p>;
}
}
export default OOO;
//end of the OOO.js file
//here is how you can use it
import CreateComponent from 'OOO.js';
const Component = CreateComponent();
const MyComponent = ()=><Component />
export default MyComponent;