react 父子組件傳值——父傳子

有興趣的小伙伴可以加Q群 879108483 互相學(xué)習(xí)

1.使用props傳值

具體實現(xiàn)

import React, { Component } from 'react';

/**父組件 */
export default class Parent extends Component {
    state = {
        msg: 1
    }
    render() {
        return (
            <div onClick={() => this.setState({ msg: this.state.msg + 1 })} >
                {/* 子組件 */}
                <Child msg={"傳遞給子組件的消息:" + this.state.msg.toString()} />
            </div>
        );
    }
}

/**子組件 */
class Child extends Component {
    // 默認(rèn)的props 可寫可不寫
    static defaultProps = {
        msg: 1
    }
    render() {
        return (
            <div>
                {/* 通過props傳遞過來的參數(shù) */}
                {this.props.msg}
            </div>
        )
    }
}

2.使用context (上下文)

Context被歸類為高級部分(Advanced),屬于React的高級API,但官方并不建議在穩(wěn)定版的App中使用Context刀崖。實際上很多優(yōu)秀的組件都是通過context來實現(xiàn)的,比如antd的主題樣式狈究。用好context可以使項目更靈活。
Context 不僅僅適用于父傳子盏求,還可以用來作為跨級傳遞數(shù)據(jù)抖锥,比如父組件傳孫子組件。如果要使用props達到這個效果就要層層傳遞props碎罚。 下面看看context實現(xiàn)方式

  1. 簡單使用 (老方法)
import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**父組件 */
export default class Parent extends Component {
    state = {
        msg: 0
    }
    // 聲明Context屬性
    static childContextTypes = {
        // 數(shù)字類型
        msg: PropTypes.number,
        // 方法
        method: PropTypes.func
    }

    // 返回Context對象磅废,約定好方法
    getChildContext() {
        return {
            msg: this.state.msg,
            method: () => "返回來的信息"
        }
    }
    render() {
        return (
            <div onClick={() => this.setState({ msg: this.state.msg + 1 })} >
                {/* 子組件 */}
                <Child />

                {/* 無狀態(tài)子組件 */}
                <ChildStateLess />
            </div>
        );
    }
}

/**子組件 */
class Child extends Component {
    // 聲明需要使用的Context屬性 必寫 不然聽過this.context.xxx 取出來的值為undefind
    static contextTypes = {
        msg: PropTypes.number
    }
    render() {
        return (
            <div>
                {/* 通過props傳遞過來的參數(shù) */}
                {this.context.msg}
                {/* 孫子組件 */}
                <GrandsonComponent />
            </div>
        )
    }
}


/**無狀態(tài)組件 */
const ChildStateLess = (props, context) => {
    return (
        <div style={{ color: "red" }} >
            {context.msg}
        </div>

    )
}
/**為無狀態(tài)組件聲明需要使用的Context屬性 */
ChildStateLess.contextTypes = {
    msg: PropTypes.number
}

/**孫子組件 */
class GrandsonComponent extends Component {
    // 聲明需要使用的Context屬性 必寫 不然聽過this.context.xxx 取出來的值為undefind
    static contextTypes = {
        msg: PropTypes.number
    }
    render() {
        return (
            <div style={{ color: "green" }} >
                {/* 通過props傳遞過來的參數(shù) */}
                {this.context.msg}
            </div>
        )
    }
}
  1. 使用<React. createContext> Api創(chuàng)建
import React from 'react';

const ExampleContext = React.createContext({
    msg: 0,
    method: () => "method"
});

此ExampleContext通過React.createContext創(chuàng)建,這個Context對象包含兩個組件荆烈,<Provider />和<Consumer />还蹲。
兩個API代替了getChildContext、childContextTypes、contextTypes這些繁瑣的api谜喊,更符合react的設(shè)計理念。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

const ExampleContext = React.createContext('ExampleContext');


class ExampleProvider extends Component {
    state = {
        msg: 0
    }
    render() {
        return (
            <div onClick={() => {
                this.setState({ msg: this.state.msg + 1 })
            }} >
                <ExampleContext.Provider value={{ msg: this.state.msg, method: () => { } }} >
                    <Child />
                    <ChildStateLess />
                </ExampleContext.Provider>
            </div>
        );
    }
}

/**子組件 */
class Child extends Component {
    render() {
        return (
            <ExampleContext.Consumer>
                {
                    (context) => (
                        <div>
                            {/* 通過props傳遞過來的參數(shù) */}
                            {context.msg}
                            {/* 孫子組件 */}
                            <GrandsonComponent />
                        </div>
                    )
                }
            </ExampleContext.Consumer>
        )
    }
}

/**無狀態(tài)組件 */
const ChildStateLess = (props, context) => {
    return (
        <ExampleContext.Consumer>
            {
                (context) => (
                    <div style={{ color: "green" }} >
                        {/* 通過props傳遞過來的參數(shù) */}
                        {context.msg}
                        {/* 孫子組件 */}
                    </div>
                )
            }
        </ExampleContext.Consumer>
    )
}
/**為無狀態(tài)組件聲明需要使用的Context屬性 */
ChildStateLess.contextTypes = {
    msg: PropTypes.number
}

/**孫子組件 */
class GrandsonComponent extends Component {
    render() {
        return (
            <ExampleContext.Consumer>
                {
                    (context) => (
                        <div style={{ color: "red" }} >
                            {/* 通過props傳遞過來的參數(shù) */}
                            {context.msg}
                            {/* 孫子組件 */}
                        </div>
                    )
                }
            </ExampleContext.Consumer>
        )
    }
}


export default ExampleProvider;
  1. 直接使用context的地方
    生命周期:
    1.componentWillReceiveProps(nextProps, nextContext)
    2.shouldComponentUpdate(nextProps, nextState, nextContext)
    3.componetWillUpdate(nextProps, nextState, nextContext)

構(gòu)造函數(shù): constructor(props, context)

web前端倦始、react交流群:879108483

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末斗遏,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子鞋邑,更是在濱河造成了極大的恐慌诵次,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件枚碗,死亡現(xiàn)場離奇詭異逾一,居然都是意外死亡,警方通過查閱死者的電腦和手機肮雨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門遵堵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人怨规,你說我怎么就攤上這事陌宿。” “怎么了波丰?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵壳坪,是天一觀的道長。 經(jīng)常有香客問我掰烟,道長爽蝴,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任纫骑,我火速辦了婚禮蝎亚,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘惧磺。我一直安慰自己颖对,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布磨隘。 她就那樣靜靜地躺著缤底,像睡著了一般。 火紅的嫁衣襯著肌膚如雪番捂。 梳的紋絲不亂的頭發(fā)上个唧,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音设预,去河邊找鬼徙歼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的魄梯。 我是一名探鬼主播桨螺,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼酿秸!你這毒婦竟也來了灭翔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤辣苏,失蹤者是張志新(化名)和其女友劉穎肝箱,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體稀蟋,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡煌张,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了退客。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骏融。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖井辜,靈堂內(nèi)的尸體忽然破棺而出绎谦,到底是詐尸還是另有隱情,我是刑警寧澤粥脚,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布窃肠,位于F島的核電站,受9級特大地震影響刷允,放射性物質(zhì)發(fā)生泄漏冤留。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一树灶、第九天 我趴在偏房一處隱蔽的房頂上張望纤怒。 院中可真熱鬧,春花似錦天通、人聲如沸泊窘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽烘豹。三九已至,卻和暖如春诺祸,著一層夾襖步出監(jiān)牢的瞬間携悯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工筷笨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留憔鬼,地道東北人龟劲。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像轴或,于是被迫代替她去往敵國和親昌跌。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355