React间的组件通信

一、父传子(props)

步骤

  1. 父组件传递数据,子组件标签身上绑定属性
  2. 子组件接收数据,props的参数

// 子组件
function Son(props) {
    return (
        <div>this is Son, {props.name}</div>
    )
}

// 父组件
function App() {
    const name = "appName"
    return (
        <div>
            <Son name={name}></Son>
        </div>
    );
}

export default App;

说明

  1. props可以传递任意的数据
  2. props是只读对象:子组件只能读取props中的数据,不能直接进行修改,父组件的数据只能由父组件修改

二、子传父

实现:子组件调用父组件的方法传参

// 子组件:结构赋值
function Son({sendMsg}) {
    const msg = "this is son msg";

    return (
        <div>
            this is Son
            <button onClick={() => sendMsg(msg)}>发送</button>
        </div>
    )
}

// 父组件
function App() {

    const getMsg = (msg) => {
        console.log("app get msg is" + msg)
    }

    return (
        <div>
            <Son sendMsg={getMsg}/>
        </div>
    );
}

export default App;


三、兄弟组件(状态提升)

实现:通过共同的父组件进行兄弟组件之间的数据传递

步骤

  1. A组件先通过子传父的方式把数据传给父组件App
  2. App拿到数据后通过父传子的方式再传递给B组件
import {useState} from "react";

// A组件:子传父
function A({sendMsg}) {
    const msg = "this is son msg";

    return (
        <div>
            this is son A
            <button onClick={() => sendMsg(msg)}>发送</button>
        </div>
    )
}

// B组件
function B({msg}) {

    return (
        <div>
            this son B
            <p>{msg}</p>
        </div>
    )
}

// 父组件
function App() {
    const [msg, setMsg] = useState();

    const getMsg = (msg) => {
        setMsg(msg)
    }

    return (
        <div>
            this App
            <A sendMsg={getMsg}></A>
            <B msg={msg}></B>
        </div>
    );
}

export default App;

四、跨层级(Context机制)

实现步骤

  1. 使用createContext方法创建一个上下文对象Ctx
  2. 在顶层组件(App)中通过Ctx.Provider组件提供数据
  3. 在底层组件(B)中通过useContext钩子函数获取消费数据
import {createContext, useContext} from "react";

// 层级关系:App -> A -> B
// 1. 使用createContext方法创建一个上下文对象Ctx
const MsgContext = createContext();

// A组件
function A() {
    return (
        <div>
            this is A
            <B></B>
        </div>
    )
}

// B组件
function B() {
    // 3. 在底层组件(B)中通过useContext钩子函数获取消费数据
    const msg = useContext(MsgContext)
    return (
        <div>
            this is B,{msg}
        </div>
    )
}

// 父组件
function App() {
    const msg = "this is app msg";

    return (
        <div>
            {/* 2. 在顶层组件(App)中通过Ctx.Provider组件提供数据 */}
            <MsgContext.Provider value={msg}>
                this App
                <A />
            </MsgContext.Provider>
        </div>
    );
}

export default App;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值