一. HOC的概念
HOC本质上是一个纯函数,只是参数和返回值都是组件,主要有以下特性:
1、抽离重复代码,实现组件复用
2、条件渲染、渲染拦截
3、拦截、组件生命周期
使用技巧:
function(componentA) { return componentB }
日常使用示例:
function HDC(WrapComponent) {
const newProps = {type: 'HCD'}; // 新的属性
return props => {
props.isShow?<WrapComponent {...props} {...newProps}/>:<div>empty</div>
}
}
function HDC(WrapComponent) {
return class extends React.Component{
constructor(props) {
super(props);
this.state={
name: ''
}
this.onChange=this.onChange.bind(this)
}
onChange=(e)=>{
this.setState({
name:e.target.value
})
}
rander() {
const newProps={
type:'HDC',
name:{
value:this.state.name,
onChange:this.onChange
}
}
return props => <WrapComponent {...props} {...newProps}/>
}
}
}
@HDC
class Example extends React.Component{
render() {
return <input value={this.props.name.value} onChange={this.props.name.onChange} />
}
}
除了上述props,state等属性声明之外,HOC组件还可用于反向继承。
反向继承(只能是类组件,函数组件没法继承<super>||可以访问到props,state,实现组件生命周期的拦截。例如计算所有组件的执行时间,总不能每个组件的生命周期都写一遍吧,那多麻烦,一般使用HOC做反向继承生命周期。
const HDC=(WrapComponent)=>{
const disMount=WrapComponent.prototype.componentDidMount;
return class extends WrapComponent{
async componentDidMount(){
if(disMount){
await disMount.apply(this)
}
//自定义事件<componentWillMount计算start,componentDidMount计算end
}
render() {
// <!-- 自定义render树-->
const tree=super.render()
const props={
...tree.props,
type:'HDC'
}
const newTree=React.cloneElement(tree,props,tree.props.children)
}
}
}
HOC实际业务场景很多,项目统一配置权限,黑白名单,以及最常见的redux的connect就属于高阶组件。