淺談React高階組件

什么是高階組件?

high-order-function(高階函數(shù))相信大多數(shù)開發(fā)者來說都熟悉,即接受函數(shù)作為參數(shù)的函數(shù),作為前端工程師的你一定接觸過這樣一個方法:map,其實map工具函數(shù)就是一個高階函數(shù)

high-order-component(高階組件)類似于高階函數(shù),即指接受React組件作為參數(shù),輸出一個新的組件的函數(shù),在這個函數(shù)中,我們可以修飾組件的props與state,所以在一些特定情況下高階組件可以讓我們的代碼看起來更優(yōu)美,更具有復用性.目前來講高階組件的實現(xiàn)方式主要有兩種:

屬性代理(props proxy):高階組件通過被包裹的React組件來操作props

反向繼承(inheritance inversion):高階組件繼承于被包裹的React組件

使用示例及一些特性

其實我也只是整理了一部分,實在是高階組件的特性比較多,這里我們直接上代碼,這樣可能看起來清晰一些,有興趣的同學可以自己通過寫一寫demo,通過console.log去看看效果(console大法好...),廢話不多說,我們先看一下前期需要準備的基本代碼:

import React from 'react';

const Button = (props) => <button>{props.children}</button> //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件
 
    render(){
        return(
            <label>{this.props.children}</label>
        )
    }
}

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                <Button>button</Button>
                <br/>
                <Label>label</Label>
            </div>
        )
    }
}
module.exports = App

以上我們先定義了三個組件,一個無狀態(tài)的Button組件,一個傳統(tǒng)的組件,一個要作為輸出的根組件,其中語法使用目前React官方推薦的ES6語法,這里著重說一下其中Button也被成為無狀態(tài)組件,我理解的無狀態(tài)組件就是指組件內部不存在state,廢話不多說了,運行下來的效果是這樣如下:

1-1.png

然后我們定義一個高階組件,代碼如下:

const HOC = (InnerComponent) => class extends React.Component{
   
    render(){
        return(
            <InnerComponent/>
        )
    }

}

就這樣一個簡易的沒有任何實際功能的高階組件就定義好了,是不是很簡單呢,那么這個高階組件要怎么使用呢?其實使用方法也很簡單,代碼如下:

const HOC = (InnerComponent) => class extends React.Component{//首字母大寫!!

    render(){
        return(
            <InnerComponent/>
        )
    }

}

const Button = HOC((props) => <button>{props.children}</button>) //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件

    render(){
        return(
            <label>{this.props.children}</label>
        )
    }
}
const LabelHoc = HOC(Label)

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                <Button>button</Button>
                <br/>
                <LabelHoc>label</LabelHoc>
            </div>
        )
    }
}
module.exports = App

這里注意下兩點:1.函數(shù)順序的問題,也就是js變量提升的問題2.也就是代碼高階組件中注釋的那個首字母大寫的問題,因為React渲染時元素分為兩重,一種是DOM元素,一種組件元素,這兩種元素在渲染時就是以首字母大小寫區(qū)分的,我們運行以上代碼的結果如下圖:

1-2.png

我們發(fā)現(xiàn)渲染下來和我們想象中有一些不同,或者說渲染的結果不對,所以我們要在高階組件render方法的時候加上這樣一行代碼如下:

const HOC = (InnerComponent) => class extends React.Component{

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

}

我們在render()時候讓props繼承到return出來的組件中,運行結果如下:

1-3.png

在寫react項目時我們會經常用到react組件的生命周期鉤子函數(shù),高階組件其實也存在生命周期,接下來我們打印一下看看高階組件生命周期執(zhí)行和參數(shù)組件的生命周期執(zhí)行的順序,(這里我們先注釋點Button組件,這樣打印結果會更清晰一些),代碼和結果如下:

const HOC = (InnerComponent) => class extends React.Component{
    componentWillMount(){
        console.log('HOC will mount')
    }
    componentDidMount(){
        console.log('HOC did mount')
    }
    render(){
        return(
            <InnerComponent
                {...this.props}
            />
        )
    }

}

const Button = HOC((props) => <button>{props.children}</button>) //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件
    componentWillMount(){
        console.log('C will mount')
    }
    componentDidMount(){
        console.log('C did mount')
    }
    render(){
        return(
            <label>{this.props.children}</label>
        )
    }
}
const LabelHoc = HOC(Label)

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                {false&&<Button>button</Button>}
                <br/>
                <LabelHoc>label</LabelHoc>
            </div>
        )
    }
}

1-4.png

這里我們可以總結出大致兩點:1.高階組件的生命周期不會影響傳入的組件2.并不是高階組件的所有生命周期都會先執(zhí)行,所以在使用高階組件需要用到生命周期鉤子時這里需要注意一下,這里我只示范了兩個生命周期,其他的生命周期大家可以自行打印看一下,附一個關于react組件生命周期的文章:
https://nsne.github.io/2017/02/15/react-component-lifecycle/#more
英語好的同學可以直接到官網查看:
https://facebook.github.io/react/docs/react-component.html
接下來我們看一看高階組件是如何修飾props于state的,我們在高階組件中新增如下代碼:

const HOC = (InnerComponent) => class extends React.Component{
    constructor(){
        super();
        this.state = {
            count:0
        }
    }

    componentWillMount(){
        console.log('HOC will mount')
    }
    componentDidMount(){
        console.log('HOC did mount')
    }
    render(){
        const newProps = this.state;
        return(
            <InnerComponent
                {...this.props}
                {...newProps}
            />
        )
    }

}

const Button = HOC((props) => <button>{props.children}-{props.count}</button>) //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件
    componentWillMount(){
        console.log('C will mount')
    }
    componentDidMount(){
        console.log('C did mount')
        console.log(this.props)
    }
    render(){
        return(
            <label>{this.props.children}-{this.props.count}</label>
        )
    }
}
const LabelHoc = HOC(Label)

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                <Button>button</Button>
                <br/>
                <LabelHoc>label</LabelHoc>
            </div>
        )
    }
}
module.exports = App

我們在高階組件新定義了一個state狀態(tài),把這個state狀態(tài)作為參數(shù)組件的newProps,我們在組件中把這個newProps渲染顯示在頁面中,最終運行結果如下:


1-5.png

證明我們可以通過高階組件給參數(shù)組件新增props,我們也可以傳方法到參數(shù)組件中,我們接下來實現(xiàn)一個簡單的點擊計數(shù)功能,代碼如下:

const HOC = (InnerComponent) => class extends React.Component{
    constructor(){
        super();
        this.state = {
            count:0
        }
    }

    componentWillMount(){
        console.log('HOC will mount')
    }
    componentDidMount(){
        console.log('HOC did mount')
    }
    update = () =>{

        const {count} = this.state
        this.setState({
            count:count+1
        })
    }
    render(){
        const newProps = this.state;
        return(
            <InnerComponent
                {...this.props}
                {...newProps}
                update = {this.update}
            />
        )
    }

}

const Button = HOC((props) => <button onClick={props.update}>{props.children}-{props.count}</button>) //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件
    componentWillMount(){
        console.log('C will mount')
    }
    componentDidMount(){
        console.log('C did mount')
        console.log(this.props)
    }
    render(){
        return(
            <label>{this.props.children}-{this.props.count}</label>
        )
    }
}
const LabelHoc = HOC(Label)

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                <Button>button</Button>
                <br/>
                <LabelHoc>label</LabelHoc>
            </div>
        )
    }
}
module.exports = App

我們可以運行然后點擊button看看效果:

1-6.png

每點擊一次button顯示的數(shù)字應該是加一的,但是下面的LabelHoc組件也是由同一個高階組件包裝過的組件,但是相應的顯示數(shù)字不會改變,說明由同一個高階組件生成的新的組件間其實是相互不會影響的
最后我們在使用高階組件時還需要注意一點,就是在注入新的props的時候的命名空間問題,因為如果props元素的key值相同的話會替代原有的props,我們可以新增代碼并驗證如下:

const HOC = (InnerComponent) => class extends React.Component{

    static defaultProps = {
        n:'HOC'
    }
    constructor(){
        super();
        this.state = {
            count:0
        }
    }

    componentWillMount(){
        console.log('HOC will mount')
    }
    componentDidMount(){
        console.log('HOC did mount')
    }
    update = () =>{

        const {count} = this.state
        this.setState({
            count:count+1
        })
    }
    render(){
        const newProps = this.state;
        return(
            <InnerComponent
                {...this.props}
                {...newProps}
                update = {this.update}
            />
        )
    }

}

const Button = HOC((props) => <button onClick={props.update}>{props.children}-{props.count}</button>) //無狀態(tài)組件

class Label extends React.Component{//傳統(tǒng)組件
    static defaultProps = {
        n:'C'
    }
    componentWillMount(){
        console.log('C will mount')
    }
    componentDidMount(){
        console.log('C did mount')
        console.log(this.props)
    }
    render(){
        return(
            <label>{this.props.children}-{this.props.count}</label>
        )
    }
}
const LabelHoc = HOC(Label)

class App extends React.Component{//根組件
    render(){
        return(
            <div>
                <Button>button</Button>
                <br/>
                <LabelHoc>label</LabelHoc>
            </div>
        )
    }
}

我們打印的Label組件的props如下:

1-7.png

其中n被覆蓋為高階組件傳入的n

寫在最后

到此為止應該初步的了解了React高階組件的一些基礎,筆者應該算是一個前端菜鳥,由于工作需要所以接觸的react,以上這些也都是查閱資料加踩坑總結出來的一點東西,希望能對初入react的新手們提供一點點的幫助,筆者代碼和文字功底有限,如果代碼有問題的話請下方留言,我好及時糾正過來以免誤導他人,順便安利一本書<深入React技術棧>作者是陳屹,我始終認為評價書好不好的一個重要因素就是是否通俗易懂,文中有一些文字也都是這本書中講的,后續(xù)有時間的話我還會分享下別的東西,最后筆者郵箱:
tzn_goodjob@163.com
最后的最后不要臉一下,如果你覺得這篇文章對你有幫助的話還請動動手點個贊,因為我比較愛慕虛榮0.0

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容