loading

React - 组件之间的通信

子组件向父组件通信

  • 子组件调用 prop 函数,并传值。
  • 父组件传递 prop 函数,通过回调函数获取值。

本质是通过回调函数进行子向父通信,子组件通过触发由父组件传递的 prop 函数,父组件执行该 prop 函数内的回调函数。

file:[子组件向父组件通信]
function Son({ onGetMsg }) {
  // 1. 数据由子组件提供,向父组件传值
  const sonMsg = "this is son msg";

  return (
    <div>
      this is Son
      <!-- 2. onClick 触发 prop 函数,将值传递给它 -->
      <button onClick={() => onGetMsg(sonMsg)}>sendMsg</button>
    </div>
  );
}

function App() {
  // 3. 传递给子组件,触发时执行回调函数,msg 获取值
  const getSonMsg = (msg) => {
    console.log(msg);
  };

  return (
    <div>
      <Son onGetMsg={getSonMsg} />
    </div>
  );
}

export default App;

嵌套组件之间通信

  • 通过 createContext 创建上下文对象。
  • 顶层组件通过 <Context.Provider></Context.Provider/> 包裹,并提供 value。
  • 需要的组件中通过 useContext 获取值。
file:[嵌套组件通信]
import { createContext, useContext } from "react";

const Context = createContext();

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

function B() {
  const ctx = useContext(Context);
  return <div>this is B component.{ctx}</div>;
}

function App() {
  const msg = "this is a app msg.";
  return (
    <div>
      <Context.Provider value={msg}>
        <A />
      </Context.Provider>
    </div>
  );
}

export default App;
posted @ 2024-03-29 19:19  Himmelbleu  阅读(5)  评论(0编辑  收藏  举报