REACT的HOC高阶组件使用场景及用法

 一. 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就属于高阶组件。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值