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)

  • 22
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值