HOC in Depth > Higher-Order Components
Higher-Order Components
https://reactjs.org/docs/higher-order-components.html
1. wrapper
props-proxy
https://codesandbox.io/s/react-hoc-in-depth-l8x1u?file=/src/components/hoc/props-proxy.jsx
import React, { Component } from "react";
function PropsProxyHOC(WrappedComponent) {
return class PPHOC extends Component {
constructor(props) {
super(props);
this.state = {
name: ""
};
this.onNameChange = this.onNameChange.bind(this);
}
onNameChange(event) {
this.setState({
name: event.target.value
});
}
render() {
const newProps = {
value: this.state.name,
onChange: this.onNameChange
};
// return <WrappedComponent {...this.props} {...newProps} />;
const mergedProps = {
this.props,
newProps
};
return <WrappedComponent {mergedProps} />;
}
};
}
export default PropsProxyHOC;
// @PPHOC
// class Example extends React.Component {
// render() {
// return <input name="name" {...this.props.name}/>
// }
// }
2. enhancer
inheritance-inversion
import React from "react";
function InheritanceInversionHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
const elementsTree = super.render();
let newProps = {};
if (elementsTree && elementsTree.type === "input") {
newProps = {
value: "may the force be with you"
};
}
// const props = Object.assign({}, elementsTree.props, newProps);
const props = {
elementsTree.props,
newProps
};
const newElementsTree = React.cloneElement(
elementsTree,
props,
elementsTree.props.children
);
return newElementsTree;
}
};
}
export default InheritanceInversionHOC;