《十》高阶组件

高阶组件:Higher-Order-Component,简称 HOC,就是参数为组件,返回值为新组件的函数。高阶组件对原组件进行了一层拦截,就可以对原组件进行各种增强了。

高阶组件也有其缺点:HOC 需要对原组件进行包裹,如果大量使用 HOC,将会产生非常多的嵌套,会让调试变得困难;而且 HOC 可以劫持 pros,在不遵守约定的情况下可能会造成 props 的冲突。

高阶组件并不是 React API 的一部分,而是一种基于 React 的组合特性而形成的设计模式。

React.memo()React.forwardRef() 都是高阶函数。

// 定义高阶组件
function hoc(wrappedComponent) {
  class enhancedComponent extends React.PureComponent {
    render() {
      // 高阶组件相当于对原组件进行了一层拦截,就可以对其进行增强了
      return <wrappedComponent />
    }
  }

  return enhancedComponent
}

// 使用高阶组件
const EnhancedComponent = hoc(WrappedComponent)

高阶组件的实现案例:通过高阶组件为自定义组件统一注入用户信息作为其 props。

// 定义高阶组件
function hoc(WrappedComponent) {
  class EnhancedComponent extends React.PureComponent {
    state = {
      userInfo: {
        name: 'Lee',
        age: 18,
      }
    }

    render() {
      // 对原组件进行拦截,将 this.state.userInfo 作为 props 注入进行增强
      return <WrappedComponent {...this.props} {...this.state.userInfo} />
    }
  }

  return EnhancedComponent
}


// 定义原组件
function Profile(props) {
  return <h1>Profile:{props.name} - {props.age}</h1>
}
// 使用高阶组件,生成增强后的组件
const EnhancedProfile = hoc(Profile)


// 使用增强后的组件
class App extends React.PureComponent {
  render() {
    return <EnhancedProfile/>
  }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值