React高阶组件

HOC —— 高阶组件

2017-09-29  本文已影响0人  rangel

本文章将从四个方面讲解高阶组件

  1. 什么是高阶组件?
  2. 高阶组件是为了解决什么问题?
  3. 常见用法
  4. 与父组件的区别

什么是高阶组件?

高阶组件的定义是类比于 高阶函数(HOF) 的定义。高阶函数接收函数作为参数,并且返回值也是一个函数。类似的,高阶组件接收React组件作为参数,并且返回一个新的React组件。

高阶函数举例:

function add(x){
  return function(y){
     return y + x;
  };
}

add(10)(11);  

使用函数式编程的写法:

const add = x => y => y + x;
高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件

a higher-order component is a function that takes a component and returns a new component

高阶组件是为了解决什么问题?

大家先看下面这个例子,该代码的功能是从localStorage中取出data数据,并且由组件渲染到页面上。

import React, { Component } from 'react'

class MyComponent extends Component {

  componentWillMount() {
      let data = localStorage.getItem('data');
      this.setState({data});
  }
  render() {
    return <div>{this.state.data}</div>
  }
}

假设现在另一个组件也要从localStorage中获取data,并切渲染到页面上,这个时候我们要写的代码和上面的代码其实一模一样,只不过是组件名字不一样而已,这样我们会写很多重复的代码。

如果使用高阶组件我们会怎么解决这个问题?

import React, { Component } from 'react'

function getLocalStorageDate(WrappedComponent) {
  return class extends Component {
    componentWillMount() {
      let data = localStorage.getItem('data');
        this.setState({data});
    }

    render() {
      // 通过{...this.props} 把传递给当前组件的属性继续传递给被包装的组件WrappedComponent
      return <WrappedComponent data={this.state.data} {...this.props} />
    }
  }
}

class MyComponent2 extends Component {  
  render() {
    return <div>{this.props.data}</div>
  }
}

const ComponentWithLocalStorage = getLocalStorageDate(MyComponent2)

在这个例子中 getLocalStorageDate便是一个高阶组件,它接收了MyComponent2组件,返回的组件是ComponentWithLocalStorage, 并且在ComponentWithLocalStorage中我们可以使用this.props.data来获取data的值,如果其他的组件同样想获取data的值,只需要将组件传给getLocalStorageDate便可。

HOC 并不会修改输入组件,也不会使用继承来复制其行为。相反,HOC 通过将原始组件 包装 在容器组件中来组合。

从这个例子中我们可以看出:

高阶组件的主要功能是封装并分离组件的通用逻辑,让通用逻辑在组件间更好地被复用(文档上说的是解决交叉问题)

高阶组件的参数并非只能是一个组件,它还可以接收其他参数

例如: 现在某个组件要取出localStorage中key为name的数据。我们可以让它接收额外的一个参数,来决定从LocalStorage中获取哪个数据:

import React, { Component } from 'react'

function withPersistentData(WrappedComponent, key) {
  return class extends Component {
    componentWillMount() {
      let data = localStorage.getItem(key);
        this.setState({data});
    }

    render() {
      // 通过{...this.props} 把传递给当前组件的属性继续传递给被包装的组件WrappedComponent
      return <WrappedComponent data={this.state.data} {...this.props} />
    }
  }
}

class MyComponent2 extends Component {  
  render() {
    return <div>{this.props.data}</div>
  }

  //省略其他逻辑...
}

class MyComponent3 extends Component {  
  render() {
    return <div>{this.props.data}</div>
  }

  //省略其他逻辑...
}

const MyComponent2WithPersistentData = withPersistentData(MyComponent2, 'data');
const MyComponent3WithPersistentData = withPersistentData(MyComponent3, 'name');

HOC常见用法

高阶组件最常见的函数签名形式是这样的:

HOC([param])([WrappedComponent])

比如:

// React Redux's `connect`
const ConnectedComment = connect(commentSelector, commentActions)(CommentList)

它就相当于:

// connect is a function that returns another function
const enhance = connect(commentListSelector, commentListActions);
// The returned function is an HOC, which returns a component that is connected
// to the Redux store
const ConnectedComment = enhance(CommentList);

withRouterRedux-form 同样也用到了HOC。

当一个组件需要被多个高阶组件包裹的时候,尽量使用组合(compose)而不使用嵌套。

// Instead of doing this...
const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent))

// ... you can use a function composition utility
// compose(f, g, h) is the same as (...args) => f(g(h(...args)))
const enhance = compose(
  // These are both single-argument HOCs
  withRouter,
  connect(commentSelector)
)
const EnhancedComponent = enhance(WrappedComponent)

高阶组件和父组件的区别

有些同学可能会觉得高阶组件有些类似父组件的使用。例如,我们完全可以把高阶组件中的逻辑放到一个父组件中去执行,执行完成的结果再传递给子组件。从逻辑的执行流程上来看,高阶组件确实和父组件比较相像,但是高阶组件强调的是逻辑的抽象。高阶组件是一个函数,函数关注的是逻辑;父组件是一个组件,组件主要关注的是UI/DOM。如果逻辑是与DOM直接相关的,那么这部分逻辑适合放到父组件中实现;如果逻辑是与DOM不直接相关的,那么这部分逻辑适合使用高阶组件抽象。

关于使用高阶组件要注意的一些问题,大家可以参考官方文档

参考文章:http://www.jianshu.com/p/3fdbcef475af

上一篇 下一篇

猜你喜欢

热点阅读