兄弟組件通信
方法一:狀態提升
子組件先將數據傳遞到父組件,父組件再把數據傳到另一個子組件中。
import { useState } from "react";
// 定義A組件,向B組件發送數據
function A({ onGetMsg }) {const name = "this is A name";return (<div>this is A component<button onClick={() => onGetMsg(name)}>send</button></div>);
}
// 定義B組件,接收A組件的數據
function B(props) {return <div>this is B component this is A name {props.msg}</div>;
}function App() {let [msg, setMsg] = useState("");const getMsg = (msg) => {setMsg(msg);};return (<div>this is app,{msg}<A onGetMsg={getMsg} /><B msg={msg} /></div>);
}
運行結果:
傳遞前:
傳遞后:
方法二:使用context機制跨層級組件通信
- 使用createContext方法創建一個上下文對象Ctx
- 在頂層組件(APP)中通過Ctx.Procider組件提供數據
- 在底層組件(B)中通過useContext鉤子函數獲取數據
import { createContext, useContext, useState } from "react";
const MsgContext = createContext();
function A() {return (<div>this is A component<B /></div>);
}function B() {const msg = useContext(MsgContext);return <div>this is B component, {msg}</div>;
}
// 頂層組件
function App() {const msg = "this is app msg";return (<div>{/* vaule 提供數據 */}<MsgContext.Provider value={msg}>this is App<A /></MsgContext.Provider></div>);
}
運行結果: