53.React学习 —— 高阶组件

高阶组件(HOC higherOrderComponent)

  • 高阶组件的作用: 提供复用的状态逻辑

  • 高阶组件是什么: 高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。HOC 自身不是 React API 的一部分,它是一种基于 React 的组合特性而形成的设计模式

    • 简单理解的话: 一个拥有复用逻辑的函数,这个函数需要传入一个组件,然后返回一个增强的组件

      const EnhancedComponent = higherOrderComponent(WrappedComponent);
      
  • 高阶组件实现

    1. 调用函数,得到增强组件,渲染增强组件

      const EnhancedComponent = higherOrderComponent(WrappedComponent);
      // 注意: 
      1. 函数名一般以with开头,使用小驼峰命名法
      2. 函数中形参要采用大驼峰命名法(因为这个参数接收的是一个组件)
      3. 返回的也是一个组件,所以也要使用大驼峰命名法
      
    2. 使用es7的修饰符

      @higherOrderComponent
      class WrappedComponent extends React.Component
      
  • 高阶组件要注意的问题:

    1. 配合chrome调试工具显示组件名的问题

在这里插入图片描述

解决:

给高阶组件中返回的组件, 增加一个静态属性displayName

static displayName = `XXX(${WrappedComponent.displayName ||WrappedComponent.name ||'Component'})`

//原理: 调试工具,优先展示组件的displayName
  1. 传递props的问题

在这里插入图片描述

在这里插入图片描述

render props

render props的作用: 提供共享的状态逻辑

render props是什么: 指一种在 React 组件之间使用一个值为函数的 prop 共享代码的简单技术

简单理解: 实现多个组件状态和逻辑共享的技术(复用)

export default class App extends Component {
  render() {
    return (
      <div>
        // 原来直接在这里渲染Cat和Mouse组件
        // 使用了render props技术之后, 在这里使用封装了共享状态逻辑的组件,
        // 真正要渲染的Cat和Mouse需要当做render这个prop的返回值传进去
        <Position render={pos => <Cat {...pos} />}></Position>
        <Position render={pos => <Mouse {...pos} />}></Position>
      </div>
    )
  }
}

render props 思路分析:

  1. 将复用的状态和逻辑代码封装到一个组件中 (比如命名为Position),

    class Position extends React.Component{
        // 定义共享状态
        state = {...}
        
        // 根据具体需求逻辑定义共享逻辑代码,比如
        handle = e => {
        	this.setState({...})         
        }
        render(){
            return this.props.render(this.state)
        }
    }
    
  2. 在这个组件上添加一个render属性. render属性的值是一个函数

    <Position  render={()=>{}}/>
    
  3. 把要真正渲染到页面的组件,当做箭头函数的返回值

     <Position  render={()=><Cat />}/>
    
  4. 这个组件render的函数可以接收组件中的状态数据

     <Position  render={ pos =><Cat {...pos}/>}/>
    
  5. 在Position中通过this.props.render()得到真正要渲染的组件

    //Position组件
    render() {
        return this.props.render()
    }
    
  6. 并在在调用this.props.render的时候,将Position组件中的数据,传递给render属性指向的函数

    //Position组件
    render() {
        return this.props.render({...this.state})
    }
    
    //App组件
    // pos接收Position中传递过来的数据,然后再传递给Cat组件
     <Position render={pos => <Cat {...pos} />}></Position>
    

上一篇:组件优化
下一篇:钩子函数(Hooks)

### React 高阶组件(HOC)的概念及用法 #### 1. 定义 高阶组件(Higher-Order Component,简称 HOC)是一种常见的 React 设计模式。其本质是一个函数,该函数接受一个组件作为输入参数,并返回一个新的组件[^1]。 #### 2. 使用场景 HOC 主要用于解决以下问题: - **代码复用与模块化**:通过封装通用逻辑到 HOC 中,减少重复代码。 - **增删改 props**:可以在不改变原始组件的情况下动态调整传入的属性。 - **渲染劫持**:控制子组件的渲染行为,比如条件渲染或数据预处理[^2]。 #### 3. 实现方式 HOC 的实现主要有两种方法: ##### 3.1 属性代理(Props Proxy) 这是最常见的 HOC 实现方式之一。通过将额外的 prop 或功能注入目标组件来增强它的能力。下面是一个简单的例子: ```javascript function withLogging(WrappedComponent) { return class WithLogging extends React.Component { componentDidMount() { console.log('Component has mounted'); } componentWillUnmount() { console.log('Component will unmount'); } render() { return <WrappedComponent {...this.props} />; } }; } ``` 在这个示例中,`withLogging` 是一个 HOC,它可以为任何组件添加日志记录的功能[^3]。 ##### 3.2 反向继承(Inheritance Inversion, II) 这种方式较少见,但也可以用来创建 HOC。它涉及让父组件继承自目标组件并覆盖某些方法或状态。不过由于 JSX 和 ES6 类语法的原因,在现代开发中更推荐使用 Props Proxy 方法。 #### 4. 示例 以下是官方文档中的经典案例——如何利用 HOC 来共享状态逻辑: 假设我们有一个需要显示加载指示器的应用程序部分,则可以构建这样一个 HOC: ```javascript import React from 'react'; // 创建一个名为 `withLoadingIndicator` 的 HOC function withLoadingIndicator(WrappedComponent) { return class LoadingIndicatorWrapper extends React.Component { constructor(props) { super(props); this.state = { isLoading: true }; } async componentDidMount() { await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟异步操作 this.setState({ isLoading: false }); } render() { const { isLoading } = this.state; if (isLoading) { return <div>Loading...</div>; } return <WrappedComponent {...this.props} />; } }; } // 被包装的真实组件 const Content = () => ( <div> This is the content after loading completes. </div> ); export default withLoadingIndicator(Content); ``` 此代码片段展示了如何通过引入加载状态管理机制扩展基础组件的行为[^2]。 #### 5. 注意事项 当使用 HOC 时需注意以下几点: - 尽量保持原有组件接收到的 props 不变,除非有特殊需求才去修改它们。 - 如果项目依赖于热更新工具如 Fast Refresh,请测试确认这些特性不会破坏由 HOC 添加的新成员变量或方法[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值