美文网首页
React - 什么是高阶组件?

React - 什么是高阶组件?

作者: 我是Msorry | 来源:发表于2021-01-26 14:57 被阅读0次

props 代理

  • 通过 ref 访问实例的方法和实例本身

可以通过 ref 访问到 WrappedComponent 的实例,但为了得到引用,WrappedComponent 必须得初始渲染,需要在 HOC 的 render 方法中返回 WrappedComponent 元素。
Ref 的回调函数会在 WrappedComponent 渲染时执行,你就可以得到 WrappedComponent 的引用。这可以用来读取/添加实例的 props ,调用实例的方法。

function refsHOC(WrappedComponent) {
  return class RefsHOC extends React.Component {
    proc(wrappedComponentInstance) {
      wrappedComponentInstance.method()
    }

    render() {
      const props = Object.assign({}, this.props, {ref: this.proc.bind(this)})
      return <WrappedComponent {...props}/>
    }
  }
}
<WrappedComponent {...this.props}/>
// 等价于
React.createElement(WrappedComponent, this.props, null)
  • 用其他元素包裹 WrappedComponent
function ppHOC(WrappedComponent) {
  return class PP extends React.Component {
    render() {
      return (
        <div style={{display: 'block'}}>
          <WrappedComponent {...this.props}/>
        </div>
      )
    }
  }
}

反向继承

HOC 通过 this 访问到 WrappedComponent,意味着它可以访问到 state、props、组件生命周期方法和 render 方法

  • 渲染劫持(Render Highjacking)
    HOC 控制着 WrappedComponent 的渲染输出
function iiHOC(WrappedComponent) {
  return class Enhancer extends WrappedComponent {
    render() {
      if (this.props.loggedIn) {
        return super.render()
      } else {
        return null
      }
    }
  }
}

相关文章

  • 利用 React 高阶组件实现一个面包屑导航

    什么是 React 高阶组件 React 高阶组件就是以高阶函数的方式包裹需要修饰的 React 组件,并返回处理...

  • React 进阶之高阶组件

    高阶组件 HOC 高阶组件(HOC)是react中的高级技术,用来重用组件逻辑。但高阶组件本身并不是React A...

  • 高阶组件

    React 高阶组件HOC (Higher-Order Component) 高阶组件是react中重复使用组件逻...

  • React高阶组件

    React高阶组件 在开始聊高阶组件之前我们先来看下高阶函数和高阶组件在形式上的差异: 一、什么是装饰器模式: 要...

  • React高阶组件HOC

    高阶组件本质是函数,参数是 组件1 返回组件2,高阶组件是为了复用通用逻辑高阶组件eg:import React,...

  • React高阶组件(HOC)

    高阶组件(Higher-Order Components) 高阶组件(HOC)是 React 中用于重用组件逻辑的...

  • React与高阶组件

    什么是高阶组件 如果熟悉react的童鞋,一定或多或少听说或者使用过高阶组件(Higher Order Compo...

  • React高阶组件

    1、React高阶组件

  • ReactNative中的高阶组件(HOC)和继承详解

    ReactNative中的高阶组件(HOC)和继承详解 共同点: 高阶组件(HOC)是 React 中用于复用组件...

  • React进阶篇(一)高阶组件

    高阶组件 高阶组件(Higher Order Component,HOC)是React的一种设计模式,用于增强现有...

网友评论

      本文标题:React - 什么是高阶组件?

      本文链接:https://www.haomeiwen.com/subject/tycljktx.html