兄弟组件通信
方法一:状态提升
子组件先将数据传递到父组件,父组件再把数据传到另一个子组件中。
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>
);
}
运行结果: