面试官:说说对高阶组件的理解?应用场景?

开发 前端
在React中,高阶组件即接受一个或多个组件作为参数并且返回一个组件,本质也就是一个函数,并不是一个组件。

[[410684]]

本文转载自微信公众号「JS每日一题」,作者灰灰。转载本文请联系JS每日一题公众号。

一、是什么

高阶函数(Higher-order function),至少满足下列一个条件的函数

  1. 接受一个或多个函数作为输入
  2. 输出一个函数

在React中,高阶组件即接受一个或多个组件作为参数并且返回一个组件,本质也就是一个函数,并不是一个组件

  1. const EnhancedComponent = highOrderComponent(WrappedComponent); 

上述代码中,该函数接受一个组件WrappedComponent作为参数,返回加工过的新组件EnhancedComponent

高阶组件的这种实现方式,本质上是一个装饰者设计模式

二、如何编写

最基本的高阶组件的编写模板如下:

  1. import React, { Component } from 'react'
  2.  
  3. export default (WrappedComponent) => { 
  4.   return class EnhancedComponent extends Component { 
  5.     // do something 
  6.     render() { 
  7.       return <WrappedComponent />; 
  8.     } 
  9.   } 

通过对传入的原始组件 WrappedComponent 做一些你想要的操作(比如操作 props,提取 state,给原始组件包裹其他元素等),从而加工出想要的组件 EnhancedComponent

把通用的逻辑放在高阶组件中,对组件实现一致的处理,从而实现代码的复用

所以,高阶组件的主要功能是封装并分离组件的通用逻辑,让通用逻辑在组件间更好地被复用

但在使用高阶组件的同时,一般遵循一些约定,如下:

  • props 保持一致
  • 你不能在函数式(无状态)组件上使用 ref 属性,因为它没有实例
  • 不要以任何方式改变原始组件 WrappedComponent
  • 透传不相关 props 属性给被包裹的组件 WrappedComponent
  • 不要再 render() 方法中使用高阶组件
  • 使用 compose 组合高阶组件
  • 包装显示名字以便于调试

这里需要注意的是,高阶组件可以传递所有的props,但是不能传递ref

如果向一个高阶组件添加refe引用,那么ref 指向的是最外层容器组件实例的,而不是被包裹的组件,如果需要传递refs的话,则使用React.forwardRef,如下:

  1. function withLogging(WrappedComponent) { 
  2.     class Enhance extends WrappedComponent { 
  3.         componentWillReceiveProps() { 
  4.             console.log('Current props', this.props); 
  5.             console.log('Next props', nextProps); 
  6.         } 
  7.         render() { 
  8.             const {forwardedRef, ...rest} = this.props; 
  9.             // 把 forwardedRef 赋值给 ref 
  10.             return <WrappedComponent {...rest} ref={forwardedRef} />; 
  11.         } 
  12.     }; 
  13.  
  14.     // React.forwardRef 方法会传入 props 和 ref 两个参数给其回调函数 
  15.     // 所以这边的 ref 是由 React.forwardRef 提供的 
  16.     function forwardRef(props, ref) { 
  17.         return <Enhance {...props} forwardRef={ref} /> 
  18.     } 
  19.  
  20.     return React.forwardRef(forwardRef); 
  21. const EnhancedComponent = withLogging(SomeComponent); 

三、应用场景

通过上面的了解,高阶组件能够提高代码的复用性和灵活性,在实际应用中,常常用于与核心业务无关但又在多个模块使用的功能,如权限控制、日志记录、数据校验、异常处理、统计上报等

举个例子,存在一个组件,需要从缓存中获取数据,然后渲染。一般情况,我们会如下编写:

  1. import React, { Component } from 'react' 
  2.  
  3. class MyComponent extends Component { 
  4.  
  5.   componentWillMount() { 
  6.       let data = localStorage.getItem('data'); 
  7.       this.setState({data}); 
  8.   } 
  9.    
  10.   render() { 
  11.     return <div>{this.state.data}</div> 
  12.   } 

上述代码当然可以实现该功能,但是如果还有其他组件也有类似功能的时候,每个组件都需要重复写componentWillMount中的代码,这明显是冗杂的

下面就可以通过高价组件来进行改写,如下:

  1. import React, { Component } from 'react' 
  2.  
  3. function withPersistentData(WrappedComponent) { 
  4.   return class extends Component { 
  5.     componentWillMount() { 
  6.       let data = localStorage.getItem('data'); 
  7.         this.setState({data}); 
  8.     } 
  9.      
  10.     render() { 
  11.       // 通过{...this.props} 把传递给当前组件的属性继续传递给被包装的组件WrappedComponent 
  12.       return <WrappedComponent data={this.state.data} {...this.props} /> 
  13.     } 
  14.   } 
  15.  
  16. class MyComponent2 extends Component {   
  17.   render() { 
  18.     return <div>{this.props.data}</div> 
  19.   } 
  20.  
  21. const MyComponentWithPersistentData = withPersistentData(MyComponent2) 

再比如组件渲染性能监控,如下:

  1. class Home extends React.Component { 
  2.     render() { 
  3.         return (<h1>Hello World.</h1>); 
  4.     } 
  5. function withTiming(WrappedComponent) { 
  6.     return class extends WrappedComponent { 
  7.         constructor(props) { 
  8.             super(props); 
  9.             this.start = 0; 
  10.             this.end = 0; 
  11.         } 
  12.         componentWillMount() { 
  13.             super.componentWillMount && super.componentWillMount(); 
  14.             this.start = Date.now(); 
  15.         } 
  16.         componentDidMount() { 
  17.             super.componentDidMount && super.componentDidMount(); 
  18.             this.end = Date.now(); 
  19.             console.log(`${WrappedComponent.name} 组件渲染时间为 ${this.end - this.start} ms`); 
  20.         } 
  21.         render() { 
  22.             return super.render(); 
  23.         } 
  24.     }; 
  25.  
  26. export default withTiming(Home); 

参考文献

https://zh-hans.reactjs.org/docs/higher-order-components.html#gatsby-focus-wrapper

https://zh.wikipedia.org/wiki/%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0

https://segmentfault.com/a/1190000010307650

https://zhuanlan.zhihu.com/p/61711492

 

责任编辑:武晓燕 来源: JS每日一题
相关推荐

2021-05-31 10:35:34

TCPWebSocket协议

2021-07-07 08:36:45

React应用场景

2021-06-08 08:33:23

NodeStream数据

2021-06-07 09:41:48

NodeBuffer 网络协议

2021-09-16 07:52:18

算法应用场景

2021-11-10 07:47:49

组合模式场景

2021-11-04 06:58:32

策略模式面试

2021-08-16 08:33:26

git

2021-11-03 14:10:28

工厂模式场景

2021-11-09 08:51:13

模式命令面试

2021-11-05 07:47:56

代理模式对象

2021-06-30 07:19:36

React事件机制

2021-09-29 07:24:20

场景数据

2021-09-06 10:51:27

TypeScriptJavaScript

2021-09-28 07:12:09

测试路径

2021-11-11 16:37:05

模板模式方法

2021-11-22 23:50:59

责任链模式场景

2021-07-09 08:33:35

React组件受控

2021-10-09 10:25:41

排序应用场景

2021-09-08 07:49:34

TypeScript 泛型场景
点赞
收藏

51CTO技术栈公众号