React 高階組件

第一章 引導

image.png

學習之前要有一定的:es6基礎担敌、js面向對象編程摘盆、react的一些基礎知識

第二章 高階組件介紹

2-1 高階函數

1、高階函數的兩個基本特征

//1.函數可以做為參數被傳遞
setTimeout(function(){
  console.log(1)
},1000)

//2.函數可以作為返回值輸出
function student(name){
  return function(){
    return name
  }
}

2徒探、應用場景:
1).高階函數在時間函數的應用

setTimeout()
setInterval()

2).高階函數在ajax中的應用

$.get('/api/api.json',function(){
    console.log('獲取成功')
})

3).高階函數在數組中的應用

some()
every()
filter()
map()
forEach()
2-2 高階組件介紹

1、高階組件基本概念(High Order Component,HOC)
高階組件就是:接受一個組件作為參數并返回一個新的組件的函數
高階組件:是一個函數销斟,并不是組件
代碼演示地址:https://gitee.com/sunnyfan/react-hight-order-component.git

git clone https://gitee.com/sunnyfan/react-hight-order-component.git
cd react-hight-order-component
npm install
npm start

代碼截取

//1.組件A是公共組件庐椒,且被定義為一個高階組件(高階函數)
import React, {Component} from 'react';
function A(WrappedComponent) {
    return class A extends Component {
        render() {
            return (
                <div className="container">
                    <div className="header">
                        <span>提示</span>
                        <span>X</span>
                    </div>
                    <div className="content">
                        <WrappedComponent></WrappedComponent>
                    </div>
                </div>
            );
        }
    }
}
export default A;

//B組件
import React, {Component} from 'react';
import A from './A';
class B extends Component {
    render() {
        return (
            <div>
                B
            </div>
        );
    }
}
export default A(B);

//C組件
import React, {Component} from 'react';
import A from './A';
class C extends Component {
    render() {
        return (
            <div>
                c
            </div>
        );
    }
}
export default A(C);

應為A組件是公共組件,在B和C組件中都被使用到了蚂踊,所以可以把A抽離成為公共組件
2约谈、使用場景
多個組件都需要某個相同的功能,使用高階組件減少重復實現
3犁钟、高階組件實例
react-redux中的connect
export default connect(mapStateToProps,mapDispatchToProps)(Header);

第三章 高階組價實現

3-1編寫高階組件

1.實現一個普通組件
2.將普通組件使用函數包裹

//第一步:實現一個普通組件
import React, {Component} from 'react';
class A extends Component {
    render() {
        return (
            <div>
                A
            </div>
        );
    }
}
export default A;

//將普通組件使用函數包裹
import React, {Component} from 'react';
function A(WrappedComponent) {
    return class A extends Component {
        render() {
            return (
                <div className="container">
                        <WrappedComponent />
                </div>
            );
        }
    }
}
export default A;
3-1使用高階組件

1.higherOrderComponent(WrappedComponent);
2.@higherOrderComponent 通過裝飾器
要想使用裝飾器的用法:那么我們需要對項目進行一些配置
1).開啟webpack配置項

在創(chuàng)建的create-react-app項目中 運行 npm run eject

2).安裝兩個依賴包

npm install babel-preset-stage-2 -D
npm install babel-preset-react-native-stage-0 -D

或者(簡寫如下):
npm install babel-preset-stage-2  babel-preset-react-native-stage-0  -D

3).項目根目錄創(chuàng)建.babelrc配置文件

//.babelrc
{
"presets":["react-native-stage-0/decorator-support"]
}

ps:如果上面出現報錯
Cannot find module 'react-native-stage-0/decorator-suppor

npm install metro-react-native-babel-preset -D
將.babelrc改為
{
  "presets": ["module:metro-react-native-babel-preset"],
   "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }]   
  ]
}

配置好后棱诱,那么怎么在項目中使用@裝飾器來替代寫法呢

import React, {Component} from 'react';
import A from './A';

@A  //第二種使用方法:通過裝飾器
class B extends Component {
    render() {
        return (
            <div>
                B
            </div>
        );
    }
}

//export default A(B);  第一種使用方法:高階組件的普通使用
export default B //如果上面使用了@A 那么這個地方直接這樣寫即可

第四章高階組件的應用

4-1 高階組件的代理方式

1、代理方式的高階組件
返回的新組件類直接繼承自React.Component
新組件扮演的角色傳入參數組件的一個代理涝动,在新組件的render函數中迈勋,將被包裹組件渲染出來,除了高階組件自己要做的工作醋粟,其他功能全局轉手給了被包裹的組件

  • 操縱prop
  • 抽離狀態(tài)
  • 訪問ref
  • 包裝組件
    1.1.操縱props
    高階組件是如何向子組件傳遞參數或者值的呢靡菇?
    高階組件是如何去除組件當中的屬性或者值的呢?
import React, {Component} from 'react';
function A(WrappedComponent) {
    return class A extends Component {
        render() {
            const {age, ...otherProps} = this.props
            return (
                <div className="container">
                    <div className="header">
                        <span>提示</span>
                        <span>X</span>
                    </div>
                    <div className="content">
                        <WrappedComponent 
                          name={'張三'} 
                          sex={'男'} 
                          {...otherProps} 
                        />
                    </div>
                </div>
            );
        }
    }
}
export default A;

通過屬性值 給子組件傳值:age={'18'}
通過結構的方式去除米愿,其他的參數或者屬性:

//這樣就把age的屬性從所有屬性值剔除出去了
const {age, ...otherProps} = this.props;
 <WrappedComponent 
    name={'張三'} 
    sex={'男'} 
    {...otherProps} 
/>

1.2.訪問ref

//A組件
import React, {Component} from 'react';
function A(WrappedComponent) {
    return class A extends Component {
        componentDidMount() {
            const value = this.refs
            console.log(value.getName())
        }      
        render() {
            const {age, ...otherProps} = this.props
            return (
                <div className="container">
                    <div className="header">
                        <span>提示</span>
                        <span>X</span>
                    </div>
                    <div className="content">
                        <WrappedComponent
                            name={'張三'}
                            sex={'男'}
                            {...otherProps}
                            ref={(value) => this.refs = value}>
                        </WrappedComponent>
                    </div>
                </div>
            );
        }
    }
}
export default A;

//B組件
import React, {Component} from 'react';
import A from './A';

@A
class B extends Component {
    getName() {
        return '我是B組件'
    }

    render() {
        const {name, age, sex} = this.props;
        return (
            <div>
                B
            </div>
        );
    }
}

export default B;

1.3 抽取狀態(tài)

//A組件
import React, {Component} from 'react';

function A(WrappedComponent) {
    return class A extends Component {
        constructor(props) {
            super(props);
            this.state = {
                inputValue: '張三'
            }
        }

        handleChangeValue = (e) => {
            const value = e.target.value;
            this.setState({
                inputValue: value
            })
        }

        render() {
            const {age, ...otherProps} = this.props;
            const {inputValue} = this.state;
            const newProps = {
                value: inputValue,
                onChange: this.handleChangeValue,
                placeholder: '張三'
            }
            return (
                <div className="container">
                    <div className="header">
                        <span>提示</span>
                        <span>X</span>
                    </div>
                    <div className="content">
                        <WrappedComponent
                            name={'張三'}
                            sex={'男'}
                            {...otherProps}
                            {...newProps}
                        />
                    </div>
                </div>
            )
                ;
        }
    }
}
export default A;

//B組件
import React, {Component} from 'react';
import A from './A';

@A
class B extends Component {
    render() {
        const {age, sex, ...newProps} = this.props;
        return (
            <div>
                <p>
                    <label>請輸入我的名字:</label>
                    <input
                        type="text"
                        value={newProps.value}
                        onChange={newProps.onChange}
                        placeholder={newProps.placeholder}
                    />
                </p>
                <p>
                    我的名字:{newProps.value}
                </p>
            </div>
        );
    }
}
export default B;

4-2 繼承方式的高階組件
采用繼承關聯作為參數的組件和返回的組件厦凤,假如傳入的組件參數是WrappedComponent,那么返回的組件就直接繼承自WrappedComponent
2.1代理方式的高階組件和繼承方式的高階組件的區(qū)別

區(qū)別

  • 操作props
  • 操作生命周期函數
//組件D 繼承方式的高階組件
import React from 'react';
const modifyPropsHOC = (WrappedComponent) => class NewComponent extends WrappedComponent {
    componentWillMount() {
        alert('我是在繼承生命周期函數')
    }
    render() {
        const element = super.render();
        const newStyle = {
            color: element.type === 'div' ? 'red' : 'green'
        };
        const newProps = {...this.props, style: newStyle};
        return React.cloneElement(element, newProps, element.props.children)
    }
};
export default modifyPropsHOC

//E組件 繼承D里面一些
import React, {Component} from 'react';
import D from './D';

@D
class E extends Component {
    componentWillMount() {
        alert('我是原始生命周期函數')
    }
    render() {
        return (
            <div>
                我是div
            </div>
        );
    }
}
export default E;

ps:我們應該“代理方式”優(yōu)先于“繼承方式”的
所以我們在開發(fā)過程中育苟,盡量是用代理方式的高階組件
4-3高階組件顯示名
通過高階組件中有一個displayName的屬性來顯示的

import React from 'react';

const modifyPropsHOC = (WrappedComponent) => class NewComponent extends WrappedComponent {
    static displayName = `NewComponent(${getDisplayName(WrappedComponent)})`; //這里設置組件名稱

    render() {
        const element = super.render();
        const newStyle = {
            color: element.type === 'div' ? 'red' : 'green'
        };
        const newProps = {...this.props, style: newStyle};
        return React.cloneElement(element, newProps, element.props.children)
    }
};

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

export default modifyPropsHOC
效果

第五章 高階組件的實際應用-底部導航切換

效果圖

代碼地址

git clone https://gitee.com/sunnyfan/react-hight-order-component.git
git checkout feature/shili
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末较鼓,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子宙搬,更是在濱河造成了極大的恐慌笨腥,老刑警劉巖拓哺,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勇垛,死亡現場離奇詭異,居然都是意外死亡士鸥,警方通過查閱死者的電腦和手機闲孤,發(fā)現死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來烤礁,“玉大人讼积,你說我怎么就攤上這事〗抛校” “怎么了勤众?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長鲤脏。 經常有香客問我们颜,道長吕朵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任窥突,我火速辦了婚禮努溃,結果婚禮上,老公的妹妹穿的比我還像新娘阻问。我一直安慰自己梧税,他們只是感情好,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布称近。 她就那樣靜靜地躺著第队,像睡著了一般。 火紅的嫁衣襯著肌膚如雪煌茬。 梳的紋絲不亂的頭發(fā)上斥铺,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天,我揣著相機與錄音坛善,去河邊找鬼晾蜘。 笑死,一個胖子當著我的面吹牛眠屎,可吹牛的內容都是我干的剔交。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼改衩,長吁一口氣:“原來是場噩夢啊……” “哼岖常!你這毒婦竟也來了?” 一聲冷哼從身側響起葫督,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤竭鞍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后橄镜,有當地人在樹林里發(fā)現了一具尸體偎快,經...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年洽胶,在試婚紗的時候發(fā)現自己被綠了晒夹。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡姊氓,死狀恐怖丐怯,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情翔横,我是刑警寧澤读跷,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站禾唁,受9級特大地震影響效览,放射性物質發(fā)生泄漏些膨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一钦铺、第九天 我趴在偏房一處隱蔽的房頂上張望订雾。 院中可真熱鬧,春花似錦矛洞、人聲如沸洼哎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽噩峦。三九已至,卻和暖如春抽兆,著一層夾襖步出監(jiān)牢的瞬間识补,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工辫红, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留凭涂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓贴妻,卻偏偏與公主長得像切油,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子名惩,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內容

  • 在目前的前端社區(qū)澎胡,『推崇組合,不推薦繼承(prefer composition than inheritance)...
    Wenliang閱讀 77,680評論 16 125
  • 前言 學習react已經有一段時間了戚宦,期間在閱讀官方文檔的基礎上也看了不少文章,但感覺對很多東西的理解還是不夠深刻...
    Srtian閱讀 1,660評論 0 7
  • React進階之高階組件 前言 本文代碼淺顯易懂熙涤,思想深入實用阁苞。此屬于react進階用法困檩,如果你還不了解react...
    流動碼文閱讀 1,186評論 0 1
  • title: react-高階組件date: 2018-07-11 09:42:35tags: web 組件間抽象...
    Kris_lee閱讀 25,996評論 2 21
  • 高階組件是對既有組件進行包裝祠挫,以增強既有組件的功能。其核心實現是一個無狀態(tài)組件(函數)悼沿,接收另一個組件作為參數等舔,然...
    柏丘君閱讀 3,074評論 0 6