【React】组件通信 - 跨层通信

组件通信 - 跨层通信

实现方式

  • 使用 centext 机制

实现步骤

  • 使用 createContext 方法创建一个上下文对象Ctx
  • 在顶层组件(如App,即提供数据方)中通过 Ctx.Provider 组件提供数据
  • 在底层组件(B)中通过 useContext 钩子函数获取消费数据

示例

import { createContext, useContext } from "react"

// 1. 使用 creatContext 创建一个上下文对象
const MsgContext = createContext()

function A() {
  return (
    <div>
      this is A component,
      <B />
    </div>
  )
}

function B() {
  // 3. 在底层组件,通过 useContext 钩子函数使用时数据
  const msg = useContext(MsgContext)
  return (
    <div>
      this is B component,{msg}
    </div>
  )
}

function App() {

  const msg = 'this is app msg'

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

export default App;
posted @ 2024-09-02 02:37  505donkey  阅读(71)  评论(0)    收藏  举报