目录
一、基本概念
二、使用场景
1.操纵 props
2.通过 ref 访问组件实例
3.组件状态提升
三、参数传递
四 、继承方式实现高阶组件
首页 web前端 js教程 React高级组件是什么?React高级组件的详细讲解

React高级组件是什么?React高级组件的详细讲解

Sep 14, 2018 pm 01:55 PM
react.js

本篇文章给大家带来的内容是关于React高级组件是什么?React高级组件的详细讲解,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

一、基本概念

高级函数是以函数为参数,并且返回也是函数的的函数。类似的,高阶组件(简称HOC)接收 React 组件为参数,并且返回一个新的React组件。高阶组件本质也是一个函数,并不是一个组件。高阶组件的函数形式如下:

const EnhanceComponent = higherOrderComponent(WrappedComponent)
登录后复制

通过一个简单的例子解释高阶组件是如何复用的。现在有一个组件MyComponent,需要从LocalStorage中获取数据,然后渲染到界面。一般情况下,我们可以这样实现:

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 中获取同样的数据展示出来时,每个组件都需要重写一次 componentWillMount 中的代码,这显然是很冗余的。下面让我人来看看使用高阶组件改写这部分代码。

import React, { Component } from 'react'

function withPersistentData(WrappedComponent) {
  return class extends Component {
    componentWillMount() {
      let data = localStorage.getItem('data');
      this.setState({data});
    }
    render() {
      // 通过{ ...this.props} 把传递给当前组件属性继续传递给被包装的组件
      return <WrappedComponent data={this.state.data} {...this.props}/>
    }
  }
}

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

const MyComponentWithPersistentData = withPersistentData(MyComponent);
登录后复制

withPersistentData 就是一个高阶组件,它返回一个新的组件,在新组件中 componentWillMount 中统一处理从 LocalStorage 中获取数据逻辑,然后将获取到的数据通过 props 传递给被包装的组件 WrappedComponent,这样在WrappedComponent中就可以直接使用 this.props.data 获取需要展示的数据,当有其他的组件也需要这段逻辑时,继续使用 withPersistentData 这个高阶组件包装这些组件。

二、使用场景

高阶组件的使用场景主要有以下4中:
1)操纵 props
2) 通过 ref 访问组件实例
3) 组件状态提升
4)用其他元素包装组件

1.操纵 props

在被包装组件接收 props 前, 高阶组件可以先拦截到 props, 对 props 执行增加、删除或修改的操作,然后将处理后的 props 再传递被包装组件,一中的例子就是属于这种情况。

2.通过 ref 访问组件实例

高阶组件 ref 获取被包装组件实例的引用,然后高阶组件就具备了直接操作被包装组件的属性或方法的能力。

import React, { Component } from 'react'

function withRef(wrappedComponent) {
  return class extends Component{
    constructor(props) {
      super(props);
      this.someMethod = this.someMethod.bind(this);
    }

    someMethod() {
      this.wrappedInstance.comeMethodInWrappedComponent();
    }

    render() {
      // 为被包装组件添加 ref 属性,从而获取组件实例并赋值给 this.wrappedInstance
      return <wrappedComponent ref={(instance) => { this.wrappedInstance = instance }} {...this.props}/>
    }
  }
}
登录后复制

当 wrappedComponent 被渲染时,执行 ref 的回调函数,高阶组件通过 this.wrappedInstance 保存 wrappedComponent 实例引用,在 someMethod 中通过 this.wrappedInstance 调用 wrappedComponent 中的方法。这种用法在实际项目中很少会被用到,但当高阶组件封装的复用逻辑需要被包装组件的方法或属性的协同支持时,这种用法就有了用武之地。

3.组件状态提升

高阶组件可以通过将被包装组件的状态及相应的状态处理方法提升到高阶组件自身内部实现被包装组件的无状态化。一个典型的场景是,利用高阶组件将原本受控组件需要自己维护的状态统一提升到高阶组件中。

import React, { Component } from 'react'

function withRef(wrappedComponent) {
  return class extends Component{
    constructor(props) {
      super(props);
      this.state = {
        value: ''
      }
      this.handleValueChange = this.handleValueChange.bind(this);
    }

    handleValueChange(event) {
      this.this.setState({
        value: event.EventTarget.value
      })
    }

    render() {
      // newProps保存受控组件需要使用的属性和事件处理函数
      const newProps = {
        controlledProps: {
          value: this.state.value,
          onChange: this.handleValueChange
        }
      }
      return <wrappedComponent {...this.props} {...newProps}/>
    }
  }
}
登录后复制

这个例子把受控组件 value 属性用到的状态和处理 value 变化的回调函数都提升到高阶组件中,当我们再使用受控组件时,就可以这样使用:

import React, { Component } from 'react'

function withControlledState(wrappedComponent) {
  return class extends Component{
    constructor(props) {
      super(props);
      this.state = {
        value: ''
      }
      this.handleValueChange = this.handleValueChange.bind(this);
    }

    handleValueChange(event) {
      this.this.setState({
        value: event.EventTarget.value
      })
    }

    render() {
      // newProps保存受控组件需要使用的属性和事件处理函数
      const newProps = {
        controlledProps: {
          value: this.state.value,
          onChange: this.handleValueChange
        }
      }
      return <wrappedComponent {...this.props} {...newProps}/>
    }
  }
}


class  SimpleControlledComponent extends React.Component {
  render() {
    // 此时的 SimpleControlledComponent 为无状态组件,状态由高阶组件维护
    return <input name="simple" {...this.props.controlledProps}/>
  }
}

const ComponentWithControlledState = withControlledState(SimpleControlledComponent);
登录后复制

三、参数传递

高阶组件的参数并非只能是一个组件,它还可以接收其他参数。例如一中是从 LocalStorage 中获取 key 为 data的数据,当需要获取数据的 key不确定时,withPersistentData 这个高阶组件就不满足需要了。我们可以让它接收一个额外参数来决定从 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} 把传递给当前组件属性继续传递给被包装的组件
      return <WrappedComponent data={this.state.data} {...this.props} />
    }
  }
}

class MyComponent extends Component {
  render() {
    return <p>{this.props.data}</p>
  }
}
// 获取 key='data' 的数据
const MyComponent1WithPersistentData = withPersistentData(MyComponent, 'data');

// 获取 key='name' 的数据
const MyComponent2WithPersistentData = withPersistentData(MyComponent, 'name');
登录后复制

新版本的 withPersistentData 满足获取不同 key 值的需求,但实际情况中,我们很少使用这种方式传递参数,而是采用更加灵活、更具能用性的函数形式:

HOC(...params)(WrappedComponent)
登录后复制

HOC(...params) 的返回值是一个高阶组件,高阶组件需要的参数是先传递 HOC 函数的。用这种形式改写 withPersistentData 如下(注意:这种形式的高阶组件使用箭头函数定义更为简洁):

import React, { Component } from 'react'

const withPersistentData = (key) => (WrappedComponent) => {
  return class extends Component {
    componentWillMount() {
      let data = localStorage.getItem(key);
      this.setState({ data });
    }
    render() {
      // 通过{ ...this.props} 把传递给当前组件属性继续传递给被包装的组件
      return <WrappedComponent data={this.state.data} {...this.props} />
    }
  }
}

class MyComponent extends Component {
  render() {
    return <p>{this.props.data}</p>
  }
}
// 获取 key='data' 的数据
const MyComponent1WithPersistentData = withPersistentData('data')(MyComponent);

// 获取 key='name' 的数据
const MyComponent2WithPersistentData = withPersistentData('name')(MyComponent);
登录后复制

四 、继承方式实现高阶组件

前面介绍的高阶组件的实现方式都是由高阶组件处理通用逻辑,然后将相关属性传递给被包装组件,我们称这种方式为属性代理。除了属性代理外,还可以通过继承方式实现高阶组件:通过 继承被包装组件实现逻辑的复用。继承方式实现的高阶组件常用于渲染劫持。例如,当用户处于登录状态时,允许组件渲染,否则渲染一个空组件。代码如下:

function withAuth(WrappedComponent) {
  return class extends WrappedComponent {
    render() {
      if (this.props.loggedIn) {
        return super.render();
      } else {
        return null;
      }
    }
  }
}
登录后复制

根据 WrappedComponent的  this.props.loggedIn 判读用户是否已经登录,如果登录,就通过 super.render()调用 WrappedComponent 的 render 方法正常渲染组件,否则返回一个 null, 继承方式实现高阶组件对被包装组件具有侵入性,当组合多个高阶使用时,很容易因为子类组件忘记通过 super调用父类组件方法而导致逻辑丢失。因此,在使用高阶组件时,应尽量通过代理方式实现高阶组件。

相关推荐:

超级给力的JavaScript的React框架入门教程_基础知识

MySQL高可用组件MHA参数详解

以上是React高级组件是什么?React高级组件的详细讲解的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

React父组件怎么调用子组件的方法 React父组件怎么调用子组件的方法 Dec 27, 2022 pm 07:01 PM

调用方法:1、类组件中的调用可以利用React.createRef()、ref的函数式声明或props自定义onRef属性来实现;2、函数组件、Hook组件中的调用可以利用useImperativeHandle或forwardRef抛出子组件ref来实现。

深入理解React的自定义Hook 深入理解React的自定义Hook Apr 20, 2023 pm 06:22 PM

React 自定义 Hook 是一种将组件逻辑封装在可重用函数中的方式,它们提供了一种在不编写类的情况下复用状态逻辑的方式。本文将详细介绍如何自定义封装 hook。

怎么调试React源码?多种工具下的调试方法介绍 怎么调试React源码?多种工具下的调试方法介绍 Mar 31, 2023 pm 06:54 PM

怎么调试React源码?下面本篇文章带大家聊聊多种工具下的调试React源码的方法,介绍一下在贡献者、create-react-app、vite项目中如何debugger React的真实源码,希望对大家有所帮助!

React为什么不将Vite作为构建应用的首选 React为什么不将Vite作为构建应用的首选 Feb 03, 2023 pm 06:41 PM

React为什么不将Vite作为构建应用的首选?下面本篇文章就来带大家聊聊React不将Vite作为默认推荐的原因,希望对大家有所帮助!

react怎么设置div高度 react怎么设置div高度 Jan 06, 2023 am 10:19 AM

react设置div高度的方法:1、通过css方式实现div高度;2、在state中声明一个对象C,并在该对象中存放更换按钮的样式,然后获取A并重新设置C中的“marginTop”即可。

7 个很棒且实用的React 组件库(压箱底分享) 7 个很棒且实用的React 组件库(压箱底分享) Nov 04, 2022 pm 08:00 PM

本篇文章给大家整理分享7 个很棒且实用的React 组件库,日常开发中经常会用到的,快来收藏试试吧!

10 个编写更简洁React代码的实用小技巧 10 个编写更简洁React代码的实用小技巧 Jan 03, 2023 pm 08:18 PM

本篇文章给大家整理分享 10 个编写更简洁 React 代码的实用小技巧,希望对大家有所帮助!

聊聊Vuex与Pinia在设计与实现上的区别 聊聊Vuex与Pinia在设计与实现上的区别 Dec 07, 2022 pm 06:24 PM

在进行前端项目开发时,状态管理始终是一个绕不开的话题,Vue 与 React 框架本身提供了一部分能力去解决这个问题。但是在开发大型应用时往往有其他考虑,比如需要更规范更完善的操作日志、集成在开发者工具中的时间旅行能力、服务端渲染等。本文以 Vue 框架为例,介绍 Vuex 与 Pinia 这两种状态管理工具在设计与实现上的区别。

See all articles