美文网首页
高阶组件实现方式

高阶组件实现方式

作者: 苍色骑士 | 来源:发表于2020-09-09 11:30 被阅读0次

参考: 深入理解高阶组件

社区推荐 组合由于继承

高阶组件的主流实现方式:

属性代理 prop proxy

  1. 添加prop

  2. ref访问被包装组件实例

  3. 提升状态,变为容器组件

  4. 和其他react元素组装UI

反向继承 inheritance inversion

  1. 渲染劫持 props.visible == true 则渲染原组件,否则不渲染内容

function iiHOC(WrappedComponent) {

  return class Enhancer extends WrappedComponent {

    render() {

      if (this.props.loggedIn) {

        return super.render()

      } else {

        return null

      }

    }

  }

}

function iiHOC(WrappedComponent) {

  return class Enhancer extends WrappedComponent {

    render() {

      const elementsTree = super.render()

      let newProps = {};

      if (elementsTree && elementsTree.type === 'input') {

        newProps = {value: 'may the force be with you'}

      }

      const props = Object.assign({}, elementsTree.props, newProps)

      const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children)

      return newElementsTree

    }

  }

}

  1. 生命周期钩子附加额外的逻辑

  2. 读取或添加state


export function IIHOCDEBUGGER(WrappedComponent) {

  return class II extends WrappedComponent {

    render() {

      return (

        <div>

          <h2>HOC Debugger Component</h2>

          <p>Props</p> <pre>{JSON.stringify(this.props, null, 2)}</pre>

          <p>State</p><pre>{JSON.stringify(this.state, null, 2)}</pre>

          {super.render()}

        </div>

      )

    }

  }

}

带参数的高阶组件


function HOCFactoryFactory(...params) {

  // do something with params

  return function HOCFactory(WrappedComponent) {

    return class HOC extends React.Component {

      render() {

        return <WrappedComponent {...this.props}/>

      }

    }

  }

}

// 使用

HOCFactoryFactory(params)(WrappedComponent)

//or

@HOCFatoryFactory(params)

class WrappedComponent extends React.Component{}

相关文章

  • 代理以及继承方式的高阶组件

    上一篇文章介绍了简单的高阶组件实现方式,接下来介绍代理和继承方式的高阶组件。 一、代理方式的高阶组件 应用场景:1...

  • react-高阶组件

    高阶组件是代码复用的一种实现方式,用以替代mixin,衍生于高阶函数,即接收一个组件并返回一个组件 基本实现(定义...

  • 高阶组件实现方式

    参考: 深入理解高阶组件 社区推荐 组合由于继承 高阶组件的主流实现方式: 属性代理 prop proxy 添加p...

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

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

  • react反向继承注意点

    react高阶组件有一种实现方式叫反向继承(Inheritance Inversion),简称II 场景:需要开发...

  • React Native创建高阶组件(修饰器)

    创建 两种方式: 代理方式的高阶组件 继承方式的高阶组件 调用 两种方式都可以包装组件、扩展生命周期方法。不同点是...

  • React--高阶组件的使用

    1.高阶函数的基本定义: 2. 高阶组件的定义方式--省略号问题 实际截图: 3.高阶组件的应用-增强props ...

  • 高阶函数 - React 中反向继承的应用

    阅读这篇文章之前,可以先拜读一下这篇文章 React 进阶之高阶组件 了解一下高阶组件的概念及几种使用方式。 高阶...

  • 高阶函数 - 属性代理在多表单中的应用

    阅读这篇文章之前,可以先拜读一下这篇文章 React 进阶之高阶组件 了解一下高阶组件的概念及几种使用方式。 高阶...

  • React-Native 高阶组件

    高阶函数 高阶组件(属性代理)普通组件还可以向高阶组件传值 高阶组件(反向继承) 普通组件的 static 方法怎...

网友评论

      本文标题:高阶组件实现方式

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