react跨组件通信Context

案例:现在有个父-子-孙组件 需要进行组件通信

复制代码
import { useState } from "react";
// 创建上下文
const CountContext = React.createContext();

//子组件
const SonComponent = (props) => {
  return (
    <div>
      <h2>子组件</h2>
      <GrandsonComponent></GrandsonComponent>
    </div>
  );
};
 

//孙组件
const GrandsonComponent= ({onGetMsg,count}) => {
  const msg=count===0?'999':0
  return (
    <div>
     <h3>孙组件</h3>
    </div>
  );
};



function App() {
   const title="hello world";
   
  const [count,setCount]=useState(0);
  return (
    <div className="App">
      <h1>父组件</h1>
      <SonComponent/>
    </div>
  );
}

export default App;

跨组件通信Context

复制代码
import { useState,useContext ,createContext } from "react";
const CountContext = createContext();

//子组件
const SonComponent = (props) => {
  return (
    <div>
      <h2>子组件</h2>
      <GrandsonComponent></GrandsonComponent>
    </div>
  );
};
 

//孙组件
const GrandsonComponent = () => {
  const { count, setCount ,otherMsg} = useContext(CountContext);
  const msg = count === 0 ? '999' : 0;
  return (
    <div>
      <h3>孙组件{count}</h3>
      <button onClick={() => setCount(msg)}>{otherMsg}</button>
    </div>
  );
};



function App() {
    
  const [count,setCount]=useState(0);
  const otherMsg='父组件的参数'
  return (
    <CountContext.Provider value={{ count, setCount,otherMsg }}>
      <div className="App">
        <h1>父组件 {count}</h1>
        <SonComponent />
      </div>
    </CountContext.Provider>
  );
}

export default App;

也是就可以实现跨组件通讯,爷爷传参或方法给孙子,孙子获得参数调用和方法了

相关推荐
kyriewen21 小时前
别再 console.log 了:5 个 Chrome DevTools 调试技巧,用过就回不去了
前端·javascript·面试
IT_陈寒1 天前
Python搞不定字符串编码?这破玩意坑我两小时!
前端·人工智能·后端
To_OC1 天前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
DigitalOcean1 天前
Laravel 开发者已在 DigitalOcean 上开通超过 10 万台服务器
前端·laravel
星始流年1 天前
从 Tool 到 Skill——基于 LangChain 的服务端Skill实现
前端·langchain·agent
李惟1 天前
开源本地通信库,纯客户端 RPC,像聊天一样通信
前端
YAwu111 天前
深入解析 React 炫彩鼠标跟随标题组件:从坐标定位到动画性能
前端·react.js
GuWenyue1 天前
排序效率低?5分钟吃透快速排序,性能飙升至O(nlogn)
前端·javascript·面试
OpenTiny社区1 天前
🎨 看完 GenUI SDK 源码我悟了!
前端·vue.js·github
叁两1 天前
前端转型AI Agent该如何学习?(前置篇)
前端·人工智能·node.js