react 高阶组件

react 高阶组件


概述

  • 目的:实现状态逻辑复用
  • 采用 包装(装饰)模式,比如说:手机壳
  • 手机:获取保护功能
  • 手机壳:提供保护功能
  • 高阶组件就相当于手机壳,通过包装组件,增强组件功能

思路分析

  • 高阶组件 (HOC , Higher-Order Component )是一个函数,接收要包装的组件,返回增强后的组件
  • 高阶组件内部创建一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给被包装组件 WrappedComponent
    在这里插入图片描述

使用步骤

  1. 创建一个函数,名称约定以with开头
  2. 指定函数参数,参数应该以大写字母开头(作为要渲染的组件)
  3. 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
  4. 在该组件中,渲染参数组件,同时将状态通过 prop 传递给参数组件
  5. 调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面中

在这里插入图片描述
在这里插入图片描述
代码示例:

import React from "react";
import ReactDOM from "react-dom";

// 高阶组件

// 创建高阶组件
function withMouse(WrappedComponent) {
    // 该组件提供复用的状态逻辑
    class Mouse extends React.Component {
        // 鼠标状态
        state = {
            x: 0,
            y: 0
        }

        handleMouseMove = e => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }

        // 控制鼠标状态的逻辑
        componentDidMount() {
            window.addEventListener('mousemove', this.handleMouseMove)
        }

        componentWillUnmount() {
            window.removeEventListener('mousemove', this.handleMouseMove)
        }

        render() {
            return (
                <WrappedComponent {...this.state}></WrappedComponent>
            )
        }

    }

    return Mouse
}

// 用来测试高阶组件
const Position = props => (
    <p>
        鼠标当前位置:(x: {props.x}, y: {props.y})
    </p>
)

const MousePosition = withMouse(Position)

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>高阶组件</h1>

                <MousePosition></MousePosition>
            </div>
        )
    }
}

// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

设置displayName

  • 使用高阶组件存在的问题∶得到的两个组件名称相同
  • 原因∶默认情况下,React使用 组件名称 作为displayName
  • 解决方式:为高阶组件设置 displayName 便于调试时区分不同的组件
  • displayName的作用∶用于设置调试信息(React Developer Tools信息)
  • 设置方式:
    在这里插入图片描述
// 创建高阶组件
function withMouse(WrappedComponent) {
    // 该组件提供复用的状态逻辑
    class Mouse extends React.Component {
        // 鼠标状态
        state = {
            x: 0,
            y: 0
        }

        handleMouseMove = e => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }

        // 控制鼠标状态的逻辑
        componentDidMount() {
            window.addEventListener('mousemove', this.handleMouseMove)
        }

        componentWillUnmount() {
            window.removeEventListener('mousemove', this.handleMouseMove)
        }

        render() {
            return (
                <WrappedComponent {...this.state}></WrappedComponent>
            )
        }

    }

    // 设置displayName
    Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
    return Mouse
}

function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// 用来测试高阶组件
const Position = props => (
    <p>
        鼠标当前位置:(x: {props.x}, y: {props.y})
    </p>
)

const MousePosition = withMouse(Position)

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>高阶组件</h1>

                <MousePosition></MousePosition>
            </div>
        )
    }
}

// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

传递props

  • 问题:props丢失
  • 原因︰高阶组件没有往下传递props
  • 解决方式∶渲染 WrappedComponent时,将statethis.props一起传递给组件
  • 传递方式∶
    在这里插入图片描述
    代码示例:
import React from "react";
import ReactDOM from "react-dom";

// 创建高阶组件
function withMouse(WrappedComponent) {
    // 该组件提供复用的状态逻辑
    class Mouse extends React.Component {
        // 鼠标状态
        state = {
            x: 0,
            y: 0
        }

        handleMouseMove = e => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }

        // 控制鼠标状态的逻辑
        componentDidMount() {
            window.addEventListener('mousemove', this.handleMouseMove)
        }

        componentWillUnmount() {
            window.removeEventListener('mousemove', this.handleMouseMove)
        }

        render() {
            return (
                <WrappedComponent {...this.state} {...this.props}></WrappedComponent>
            )
        }

    }

    // 设置displayName
    Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
    return Mouse
}

function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// 用来测试高阶组件
const Position = props => {
    console.log('Position中的props', props);
    return (
        <p>
            鼠标当前位置:(x: {props.x}, y: {props.y})
        </p>
    )
}

const MousePosition = withMouse(Position)

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>高阶组件</h1>

                <MousePosition MousePosition a="1" />
            </div>
        )
    }
}

// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值