HOC in Depth
HOC in Depth
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
https://codesandbox.io/s/react-hoc-in-depth-l8x1u?file=/src/components/hoc/inheritance-inversion.jsx
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;
zh-Hans
https://github.com/reactjs/reactjs.org/blob/master/content/docs/higher-order-components.md
https://github.com/reactjs/zh-hans.reactjs.org/blob/master/content/docs/higher-order-components.md
https://github.com/reactjs/zh-hans.reactjs.org/pull/170
blogs
https://www.aneureka.cn/2018/09/18/react-hoc-implementation/
https://juejin.im/post/5b7666b1e51d45560c1554a3
https://zhuanlan.zhihu.com/p/24776678
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12813485.html
未经授权禁止转载,违者必究!