溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

React組件通信如何實現(xiàn)

發(fā)布時間:2023-03-17 09:42:42 來源:億速云 閱讀:97 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“React組件通信如何實現(xiàn)”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“React組件通信如何實現(xiàn)”文章能幫助大家解決問題。

    1. 父子組件通信方式

    父子組件之間的通信很常見,其中父組件可以通過props,原型方法向子組件通信,同時子組件也可以用回調(diào)函數(shù),事件冒泡向父組件通信

    父傳子

    原型方法

    父組件通過React.createRef()創(chuàng)建Ref,保存在實例屬性myRef上。父組件

    中,渲染子組件時,定義一個Ref屬性,值為剛創(chuàng)建的myRef。

    父組件調(diào)用子組件的myFunc函數(shù),傳遞一個參數(shù),子組件接收到參數(shù),打印出參數(shù)。

    this.props

    name作為props由父組件傳遞給子組件,子組件拿到name后,渲染在頁面上。參數(shù)有父組件傳遞給子組件

    import React, { Component, Fragment } from 'react';
    class Son extends Component {
        myFunc(name) {
            console.log(name);
        }
        render() {
            return <></>;
        }
    }
    // 父組件
    export default class Father extends Component {
        constructor(props) {
            super(props);
            // 創(chuàng)建Ref,并保存在實例屬性myRef上
            this.myRef = React.createRef();
        }
        componentDidMount() {
            // 調(diào)用子組件的函數(shù),傳遞一個參數(shù)
            this.myRef.current.myFunc('Jack');
        }
        render() {
            return (
                <>
                    <Son ref={this.myRef} />
                </>
            );
        }
    }

    子傳父

    • 回調(diào)函數(shù)

    • 事件冒泡

    在子組件內(nèi)部,修改了父組件中的值,從而完成了子組件向父組件通信

    import React, { Component } from 'react'
    class Navbar extends Component{
        render(){
            return <div style={{background:"red"}}>
                <button onClick={()=>{
                       console.log("子通知父, 讓父的isSHow 取反。",this.props.event) 
                       this.props.event() //調(diào)用父組件傳來啊的回調(diào)函數(shù)
                }}>click</button>
                <span>navbar</span>
            </div>
        }
    }
    class Sidebar extends Component{
        render(){
            return <div style={{background:"yellow",width:"200px"}}> 
                <ul>
                    <li>11111</li>
                </ul>
            </div>
        }
    }
    export default class App extends Component {
        state = {
            isShow:false
        }
        handleEvent = ()=>{
            this.setState({
                isShow:!this.state.isShow
            })
            // console.log("父組件定義的event事件")
        }
        render() {
            return (
                <div>
                    <Navbar event={this.handleEvent}/>
                    {/* <button onClick={()=>{
                        this.setState({
                            isShow:!this.state.isShow
                        })
                    }}>click</button> */}
                    {this.state.isShow && <Sidebar/>}
                </div>
            )
        }
    }
    /*
    父傳子 :屬性,
    子傳父: 回調(diào)函數(shù) callback
    */

    2. 非父子組件通信方式

    狀態(tài)提升

    React中的狀態(tài)提升概括來說,就是將多個組件需要共享的狀態(tài)提升到它們最近的父組件上.在父組件上改變這個狀態(tài)然后通過props

    發(fā)布訂閱模式實現(xiàn)

    context狀態(tài)樹傳參

    a. 先定義全局context對象
    import React from 'react'
    const GlobalContext = React.createContext()
    export default GlobalContext
    b. 根組件引入GlobalContext,并使用GlobalContext.Provider(生產(chǎn)者)
    //重新包裝根組件 class App {}
    <GlobalContext.Provider
    value={{
    name:"kerwin",
    age:100,
    content:this.state.content,
    show:this.show.bind(this),
    hide:this.hide.bind(this)
    }}
    >
    <之前的根組件></之前的根組件>
    </GlobalContext.Provider>
    c. 任意組件引入GlobalContext并調(diào)用context,使用GlobalContext.Consumer(消費者)
    <GlobalContext.Consumer>
    {
    context => {
    this.myshow = context.show; //可以在當前組件任意函數(shù)觸發(fā)
    this.myhide = context.hide;//可以在當前組件任意函數(shù)觸發(fā)
    return (
    <div>
    {context.name}-{context.age}-{context.content}
    </div>
    )
    }
    }
    </GlobalContext.Consumer>

    注意:GlobalContext.Consumer內(nèi)必須是回調(diào)函數(shù),通過context方法改變根組件狀態(tài)

    context優(yōu)缺點:

    優(yōu)點:跨組件訪問數(shù)據(jù)

    缺點:react組件樹種某個上級組件shouldComponetUpdate 返回false,當context更新時,不會引起下級組件更新

    關(guān)于“React組件通信如何實現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI