深入学习React高阶组件

Mixin

在了解高阶组件之前我们先讲一下mixin很多初级前端工程师对mixin的概念并不是很了解,首先解释一下mixin
mixin:在项目中有些一代码相同的代码会重复使用,我们就可以进行抽离,方便维护,为了解决这个问题就是包装成mixin方法,但是后来发现有mixin有很多弊端,也许可以说高阶组件就是mixin的衍生品,让我们进入今天的主题

高阶组件

高阶组件:本身是一个函数,这个函数接受一个组件做为参数,并且返回一个组件
实现方式:属性代理反向继承

示例:

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends Component {//返回一个组件
        render() {
            return (
                <div>
                    <h1>这是一个高阶组件</h1>
                    <WrappedComponent></WrappedComponent>
                </div>

            )
        }
    }
}

那么高阶组件有什么用?

  • 代码复用
  • 抽离state
  • 操作props
  • 获取实例
  • 布局更改
    接下来我们一个个例子查看它的好处

现在有一个组件ConfirmBox点击按钮后消失

class Dialog extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show:true,
            msg:'这是一个对话框',
            title:'对话框'
        }
    }
    handleConfirm = () => {
        this.setState({
            show:!this.state.show
        })
    }
    render() { 
        return (
            <div style={{display:this.state.show?'block':'none'}}>
                <h1>{this.state.title}</h1>
                <p>{this.state.msg}</p>
                <button  onClick={this.handleConfirm}>确认</button>
            </div>
        )
    }
}

属性代理

现在我们使用高阶组件ConfirmBox组件里的state回调函数抽离出来
属性代理可以做什么?

  • 抽离state
  • 操作props
  • 获取实例
  • 布局更改

接下来对props进行操作

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends Component {//返回一个组件
        constructor(props) {
            super(props);
            this.state = {
                show:true,
                msg:'这是一个对话框',
                title:'对话框'
            }
        }
        handleConfirm = () => {
            this.setState({
                show:!this.state.show
            })
        }
        render() {
            return (
                <div>
                    <h1>这是一个高阶组件</h1>
                    <WrappedComponent {...this.state} handleConfirm={this.handleConfirm}></WrappedComponent>
                </div>

            )
        }
    }
}
class ConfirmBox extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        return (
            <div style={{display:this.props.show?'block':'none'}}>
                <h1>{this.props.title}</h1>
                <p>{this.props.msg}</p>
                <button  onClick={this.props.handleConfirm}>确认</button>
            </div>
        )
    }
}

现在我们已经把state回调函数已经抽离到高阶组件中

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends Component {//返回一个组件
        constructor(props) {
            super(props);
            this.state = {
                show:true,
                msg:'这是一个对话框',
                title:'对话框'
            }
        }
        handleConfirm = () => {
            this.setState({
                show:!this.state.show
            })
        }
        render() {
            const newProps = {
                show:true,
                msg:'这是新的props'
            }
            return (
                <div>
                    <h1>这是一个高阶组件</h1>
                    <WrappedComponent {...newProps} title={this.state.title} handleConfirm={this.handleConfirm}></WrappedComponent>
                </div>

            )
        }
    }
}
class ConfirmBox extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        return (
            <div style={{display:this.props.show?'block':'none'}}>
                <h1>{this.props.title}</h1>
                <p>{this.props.msg}</p>
                <button  onClick={this.props.handleConfirm}>确认</button>
            </div>
        )
    }
}

到这里不知道会不会有人感觉这个和React的UI和逻辑抽离很像,其实是没错的,UI和业务逻辑拆分也类似,那为什么还要有高阶组件呢
这里需要强调一下高阶组件是函数意味着参数是动态的这一点很重要,如果有两个组件有同样的逻辑通过高阶组件只需要改变实参就可以实现而UI和业务逻辑拆分就不行。

假设:现在有一个ConfirmBox2和ComfirmBox1的逻辑一样那我们直接改变参数就可以了

Hoc(ConfirmBox2)

简单一行我们就把逻辑赋予给了ComfirmBox2
使用高阶组件相对比较灵活,这里我可能找的例子不好,请各位读者见谅。
通过ref访问组件实例

<WrappedComponent
                        {...newProps} title={this.state.title}
                        handleConfirm={this.handleConfirm}
                        ref={ref => this.myInstance = ref}></WrappedComponent>

这样我们就得到了组件实习了

反向继承(不推荐使用)

反向继承:既然有继承两字肯定和extends脱不了干系,反向继承就是通过继承传进来的组件参数并且在render调用super.render实现的
反向继承:可以做什么?

  • 操作state
  • 渲染劫持
    最简单例子:
function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends WrappedComponent {//继承传进来的组件
        render() {
            return (
                super.render();//调用super.render

            )
        }
    }
}

操作state:根据state的show判断是否显示组件

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends WrappedComponent {//返回一个组件
        static displayName = `HOC(${WrappedComponent.displayName || WrappedComponent.name})`
        componentWillMount() {
            // 可以方便地得到state,做一些更深入的修改。
            this.setState({
                msg: '这是hoc修改的值'
            });
        }
        render() {
            return (
                <div>
                    {  super.render()}
                </div>


            )
        }
    }
}

渲染劫持

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends WrappedComponent {//返回一个组件
        static displayName = `HOC(${WrappedComponent.displayName || WrappedComponent.name})`
        componentWillMount() {
            // 可以方便地得到state,做一些更深入的修改。
            this.setState({
                msg: '这是hoc修改的值'
            });
        }
        render() {
            if(this.state.show) {
                return super.render()
            }else {
                return null
            }
        }
    }
}

反向代理:为什么不推荐使用,因为操作state容易覆盖,并且生命周期函数也会覆盖

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class extends WrappedComponent {//返回一个组件
        static displayName = `HOC(${WrappedComponent.displayName || WrappedComponent.name})`
        componentWillMount() {
            // 可以方便地得到state,做一些更深入的修改。
            this.setState({
                msg: '这是hoc修改的值' //修改了msg的值
            });
        }
        componentDidMount(){
            console.log("hoccomponentDidMount")
        }
        render() {
            if(this.state.show) {
                return super.render()
            }else {
                return null
            }
        }
    }
}
class ConfirmBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show:true,
            msg:'这是一个对话框',
            title:'对话框'
        }
    }
    handleConfirm = () => {
        this.setState({
            show:!this.state.show
        })
    }
    componentDidMount() {
        console.log("comfirmbox    componentDidMount")
    }
    render() {
        return (
            <div style={{display:this.state.show?'block':'none'}}>
                <h1>{this.state.title}</h1>
                <p>{this.state.msg}</p>
                <button  onClick={this.state.handleConfirm}>确认</button>
            </div>
        )
    }
}

[图片上传失败...(image-83c9fd-1599201044014)]
从图片可以看出被包裹组件componentDidMount生命周期函数组覆盖了,如果要调用需要使用super.componentDidMount去调用,而且state也被覆盖了
另外最重要一点反向继承不能保证子组件完全被渲染,这是什么意思?就是被包裹组件里的可能会丢失

高阶组件使用场景

页面渲染

function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class Test extends Component {//返回一个组件
        static displayName = `HOC(${WrappedComponent.displayName || WrappedComponent.name})`
        constructor(props) {
            super(props);
            this.state = {
                show:true,
                msg:'这是一个对话框',
                title:'对话框'
            }
        }
        handleConfirm = () => {
            this.setState({
                show:!this.state.show
            })
        }
        componentDidMount() {
            console.log(this.myInstance)
        }

        render() {
            const newProps = {
                show:true,
                msg:'这是新的props'
            }
            if(this.state.show) {
                return  <WrappedComponent
                    {...newProps} title={this.state.title}
                    handleConfirm={this.handleConfirm}
                    ref={ref => this.myInstance = ref}></WrappedComponent>
            }else {
                return null
            }
           
        }
    }
}

逻辑复用:现在假设有两个确认框组件,他们的逻辑一样,只有样式不同,那我们就可以使用高阶组件来实现

import React,{Component} from 'react'

import './Hoc.css'
function Hoc(WrappedComponent) {//hoc就是是个高阶组件   接受一个组件做为参数
    return class Test extends Component {//返回一个组件
        static displayName = `HOC(${WrappedComponent.displayName || WrappedComponent.name})`
        constructor(props) {
            super(props);
            this.state = {
                show:true,
                msg:'这是一个对话框',
                title:'对话框'
            }
        }
        handleConfirm = () => {
            this.setState({
                show:!this.state.show
            })
        }
        componentDidMount() {
            console.log(this.myInstance)
        }

        render() {
            const newProps = {
                show:true,
                msg:'这是新的props'
            }
            if(this.state.show) {
                return  <WrappedComponent
                    {...newProps} title={this.state.title}
                    handleConfirm={this.handleConfirm}
                    ref={ref => this.myInstance = ref}></WrappedComponent>
            }else {
                return null
            }

        }
    }
}
class ConfirmBox extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        return (
            <div className={'confirmWrap'} style={{display:this.props.show?'block':'none'}}>
                <h1>{this.props.title}</h1>
                <p>{this.props.msg}</p>
                <button className={'btn'} onClick={this.props.handleConfirm}>确认</button>
                <button>取消</button>
            </div>
        )
    }
}
class ConfirmBox2 extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        return (
            <div className={'confirmWrap2'} style={{display:this.props.show?'block':'none'}}>
                <span>{this.props.title}</span>
                <p>{this.props.msg}</p>
                <button>取消</button>
            </div>
        )
    }
}

export  default {
    comfirmBox:Hoc(ConfirmBox),
    comfirmBox2:Hoc(ConfirmBox2)
}
image.png

在这里插入图片描述

可以看出组件只是样式不同,逻辑相同我们就可以使用高阶组件来实现逻辑复用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335