HOC定义:高阶组件(Higher - Order Component,简称 HOC)是一种在 React 中用于复用组件逻辑的高级技术。它本质上是一个函数,这个函数接收一个组件作为参数,并返回一个新的组件。返回的新组件可以在原组件的基础上添加新的功能、修改组件的行为或者修改组件的属性(props)等。
常用方式:属性代理
反向继承
import React, { Component } from "react";
export default function Hoc() {
return (
<div>
属性代理
<RedPropCard />
<BluePropCard />
反向继承
<LogComponent />
</div>
);
}
const withCard = (color) => (Component) => {
return (props) => {
const hotStyle = {
margin: "8px",
padding: "8px",
border: `1px solid #ccc`,
borderRadius: "4px",
backgroundColor: color,
};
const name = "高阶组件";
return (
<div style={hotStyle}>
<Component {...props} color={color} name={name} />
</div>
);
};
};
const PropProxy = ({ color, name }) => {
return (
<div>
<h2>this is the title ---{name}</h2>
<p>hello,my name is luyi,the backgroundColor is {color}</p>
</div>
);
};
const RedPropCard = withCard("red")(PropProxy);
const BluePropCard = withCard("blue")(PropProxy);
class Extending extends Component {
componentDidMount() {
console.log(" componentDidMount,Extends");
}
render() {
return <div>Extends</div>;
}
}
const withLog = (str) => (WarppedComponent) => {
const didmount = WarppedComponent.prototype.componentDidMount;
return class A extends WarppedComponent {
componentDidMount() {
if (didmount) {
didmount.apply(this);
}
console.log(str);
}
render() {
return super.render();
}
};
};
const LogComponent = withLog("Hello luyi")(Extending);