function Son({onGetSonMsg}) {
const sonMsg="this is son msg"
return (
<div>
this is Son
<button onClick={()=>onGetSonMsg(sonMsg)}>sendMsg </button>
</div>
)
}
function App() {
const getMsg=(msg)=>{
console.log(msg)
}
return (
<div>
this is APP
<Son onGetSonMsg={getMsg} />
</div>
);
}
export default App;
使用状态提升实现兄弟组件通信
实现思路:借助"状态提升"机制,通过父组件进行兄弟组件之间的数据传递
A组件先通过子传父的方式把数据传给父组件App
App拿到数据后通过父传子的方式再传递给B组件
javascript复制代码
// 1. 通过子传父 A -> App
// 2. 通过父传子 App -> B
import { useState } from "react"
function A ({ onGetAName }) {
// Son组件中的数据
const name = 'this is A name'
return (
<div>
this is A compnent,
<button onClick={() => onGetAName(name)}>send</button>
</div>
)
}
function B ({ name }) {
return (
<div>
this is B compnent,
{name}
</div>
)
}
function App () {
const [name, setName] = useState('')
const getAName = (name) => {
console.log(name)
setName(name)
}
return (
<div>
this is App
<A onGetAName={getAName} />
<B name={name} />
</div>
)
}
export default App
使用Context机制跨层级组件通信
实现步骤:
使用createContext方法创建一个上下文对象Ctx
在顶层组件(App)中通过 Ctx.Provider 组件 提供数据
在底层组件(B)中通过 useContext 钩子函数获取消费数据
javascript复制代码
// App -> A -> B
import { createContext, useContext } from "react"
// 1. createContext方法创建一个上下文对象
const MsgContext = createContext()
// 2. 在顶层组件 通过Provider组件提供数据
// 3. 在底层组件 通过useContext钩子函数使用数据
function A () {
return (
<div>
this is A component
<B />
</div>
)
}
function B () {
const msg = useContext(MsgContext)
return (
<div>
this is B compnent,{msg}
</div>
)
}
function App () {
const msg = 'this is app msg'
return (
<div>
<MsgContext.Provider value={msg}>
this is App
<A />
</MsgContext.Provider>
</div>
)
}
export default App