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;

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

相关推荐
支撑前端荣耀3 分钟前
从零实现前端监控告警系统:SMTP + Node.js + 个人邮箱 完整免费方案
前端·javascript·面试
重铸码农荣光7 分钟前
🎯 从零搭建一个 React Todo 应用:父子通信、状态管理与本地持久化全解析!
前端·react.js·架构
用户4099322502127 分钟前
Vue3 v-if与v-show:销毁还是隐藏,如何抉择?
前端·vue.js·后端
Mr_chiu7 分钟前
🚀 效率暴增!Vue.js开发必知的15个神级提效工具
前端
shanLion8 分钟前
Vite项目中process报红问题的深层原因与解决方案
前端·javascript
烟袅9 分钟前
从零构建一个待办事项应用:一次关于组件化与状态管理的深度思考
前端·javascript·react.js
前端小万13 分钟前
草稿
前端
闲云一鹤14 分钟前
将地图上的 poi 点位导出为 excel,并转换为 shp 文件
前端·cesium
岁月宁静1 小时前
MasterGo AI 实战教程:10分钟生成网页设计图(附案例演示)
前端·aigc·视觉设计
狗头大军之江苏分军1 小时前
快手12·22事故原因的合理猜测
前端·后端