React HOC(高阶组件)

一、定义

  高阶函数:函数接受函数作为输入,或者输出一个函数。

  高阶组件:接受React组件作为输入,或是输出一个组件。即hocFactory:: W: React.Component => E: React.Component

  高阶组件让代码更有复用性、逻辑性、抽象性。

二、实现高阶函数的三种方法。

  1. 属性继承??(将Input组件的name,onChange方法提取到高阶组件中)

const Mycontainer = (WrappedComponent) => {
    class extends React.Component {      constructor(props) {      super(props);      this.state = {       name: ‘‘,      }      this.onNameChange = this.onNameChange.bind(this);    }    onNameChange(event) {     this.state({      name: event.target.value,     })    }
      render() {     const newProps = { name:{      value: this.state.name,      onChange: this.onNameChange,     } };
        return <WrappedComponent {...this.props} {...newProps}/>;
      }
    }
}
class MyComponent extends React.Component {
  // ...
}

export default Mycontainer(MyComponent);

  2. 反向继承

  ??渲染劫持: 就是高阶组件可以控制组件渲染以及props,state等。

const MyContainer = WrappedComponent =>
  class extends WrappedComponent {
    render() {
      if (this.props.loggedIn) {
        return super.render();
      } else {
        return null;
      }
    }
  }

3. 组件参数

??调用高阶组件时需要传递一些参数

function HOCFactoryFactory(...params) {
  // 可以做一些改变params的事情
  return function HOCFactory(WrappedComponent) {
    return class HOC extends Component {
      render() {
        return <WrappedComponent {...this.props} {...params}/>
      }
    }
  }
}

HOCFactoryFactory(params)(WrappedComponent);

三、使用高阶组件使组件分离,抽象逻辑。

class SelectInput extends React.Component {
  static displayName = ‘SelectInput‘;

  render() {
    const { selectedItem, isActive, onClickHeader, placeholder } = this.props;
    const { text } = selectedItem;

    return (
      <div>
        <div onClick={onClickHeader}>
          <input type="text" disabled value={text} placeholder={placeholder}/>
          <Icon className={isActive} name="angle-name"/>
        </div>
      </div>
    );
  }
}

const searchDecorator = WrappedComponent => {
  class SearchDecorator extends React.Component {
    constructor(props){
      super(props);

      this.handleSearch = this.handleSearch.bind(this);
    }

    handleSearch(keyword) {
      this.setState({
        data: this.props.data,
        keyword,
      });
      this.props.onSearch(keyword);
    }

    render() {
      const { data, keyword } = this.state;
      return (
        <WrappedComponent
          {...this.props}
          data={data}
          keyword={keyword}
          onSearch={this.handleSearch}
        />
      )
    }
  }
  return SearchDecorator;
}

const asyncSelectDecorator = WrappedComponent => {
  class AsyncSelectDecorator extends React.Component {
    componentDidMount() {
      const { url, params } = this.props;

      fetch(url, { params }).then(data => {
        this.setState({
          data,
        });
      });
    }
    render() {
      return (
        <WrappedComponent
          {...this.props}
          data={this.state.data}
        />
      )
    }
  }
  return AsyncSelectDecorator;
}

class App extends React.Component {
  render() {  const Input = searchDecorator(asyncSelectDecorator(SelectInput))
    return {
    <Input {...this.props} />
  }  } }

原文地址:https://www.cnblogs.com/fange/p/12368119.html

时间: 2024-08-30 12:42:38

React HOC(高阶组件)的相关文章

【转】react的高阶组件

前言 本文代码浅显易懂,思想深入实用.此属于react进阶用法,如果你还不了解react,建议从文档开始看起. 我们都知道高阶函数是什么, 高阶组件其实是差不多的用法,只不过传入的参数变成了react组件,并返回一个新的组件. A higher-order component is a function that takes a component and returns a new component. 形如: const EnhancedComponent = higherOrderComp

react.js 高阶组件----很简单的实例理解高阶组件思想

/* * 高阶组件其实是一个函数,传进去的一个组件,返回一个新组件 * 实现不同组件中的逻辑复用, * 将一些可以单独抽离的逻辑处理给要返回的新组件里面复用 * 然后将单独的组件,传递给新组件 * */ import React, {Component} from 'react' import ReactDOM from 'react-dom' //高阶组件定义,里面return 返回新组件 function local(Comp,key){ class Proxy extends Compon

React: 高阶组件(HOC)

一.简介 如我们所知,JavaScript有高阶函数这么一个概念,高阶函数本身是一个函数,它会接收或者返回一个函数,进而对该函数进行操作.其实,在React中同样地有高阶组件这么一个东西,称为HOC,它也是一个函数,但是与高阶函数不同的是,高阶组件操作的是组件,它会接收一个组件作为参数,然后返回另外一个组件.通常,HOC会使用一个能够维护State或者包含若干功能的类来包装输入的组件,父组件保留State或者将若干功能作为属性向下传递给参数组件,参数组件不需要知道HOC代码实现的具体细节,它允许

聊聊React高阶组件(Higher-Order Components)

使用 react已经有不短的时间了,最近看到关于 react高阶组件的一篇文章,看了之后顿时眼前一亮,对于我这种还在新手村晃荡.一切朝着打怪升级看齐的小喽啰来说,像这种难度不是太高同时门槛也不是那么低的东西如今可不多见了啊,是个不可多得的 zhuangbility的利器,自然不可轻易错过,遂深入了解了一番. 概述 高阶组件的定义 React 官网上对高阶组件的定义: 高阶部件是一种用于复用组件逻辑的高级技术,它并不是 React API的一部分,而是从React 演化而来的一种模式. 具体地说,

react高阶组件的理解

[高阶组件和函数式编程] function hello() { console.log('hello jason'); } function WrapperHello(fn) { return function() { console.log('before say hello'); fn(); console.log('after say hello'); } } // hello 这时候等于 WrapperHello函数中返回的 匿名函数 // 在设计模式中这种操作叫做 装饰器模式 // 高

react 高阶组件之小学版

高阶组件  多么高大上的概念,一般用来实现组件逻辑的抽象和复用,在很多三方库(redux)中都被使用到,但是开发普通有任务项目时,如果能合理使用高阶组件,也会显著的提高代码质量. 我们今天就用最简单的逻辑来搞一搞这个家伙 我们先看一个栗子,看看这个家伙是如何进行逻辑复用的: 现在有一个组件MyComponent,需要从LocalStorage中获取数据, 然后渲染到界面. 一般情况下,我们可以这样实现: 代码很简单,但当其他组件也需要从LocalStorage中获取同样的数据展示出来时,每个组件

高阶函数HOF和高阶组件HOC(Higher Order Func/Comp)

一.什么是高阶函数(组件),作用是什么? 子类使用父类的方法可以通过继承的方式实现,那无关联组件通信(redux).父类使用子类方法(反向继承)呢 为了解决类(函数)功能交叉/功能复用等问题,通过传入类/函数返回类/函数(继承)的方式使得类拥有自身未定义的方法. 例如react-redux的connect方法使用了高阶组件: React Redux的connect: const HOC = connnect(mapStateToProps)(Comp); // connect为柯里化函数 实际为

React组件重构:嵌套+继承 与 高阶组件

前言 在最近做的一个react项目中,遇到了一个比较典型的需要重构的场景:提取两个组件中共同的部分. 最开始通过使用嵌套组件和继承的方式完成了这次重构. 但是后来又用高阶组件重新写了一遍,发现更好一点. 在这里记录下这两种方式以便之后参考和演进. 本次重构的场景 因为场景涉及到具体的业务,所以我现在将它简化为一个简单的场景. 现在有两个黑色箱子,箱子上都有一个红色按钮,A箱子充满气体,按了按钮之后箱子里面气体变红,B箱子充满泥土,按了之后箱子里面泥土变红. 那么现在上一个简单的重构前代码: Bo

react:高阶组件wrappedComponent

什么是高阶组件? 高阶部件是一种用于复用组件逻辑的高级技术,它并不是 React API的一部分,而是从React 演化而来的一种模式. 具体地说,高阶组件就是一个接收一个组件并返回另外一个新组件的函数! 解决什么问题? 随着项目越来越复杂,开发过程中,多个组件需要某个功能,而且这个功能和页面并没有关系,所以也不能简单的抽取成一个新的组件,但是如果让同样的逻辑在各个组件里各自实现,无疑会导致重复的代码.比如页面有三种弹窗一个有title,一个没有,一个又有右上角关闭按钮,除此之外别无它样,你总不