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;

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

相关推荐
万少2 分钟前
万少用9个AI工具,帮朋友完成了一个"不可能"的项目
前端
小小小小宇4 分钟前
Vue `import` 为什么可以异步加载
前端
WMYeah9 分钟前
【无标题】
前端·rust·抽奖程序·跨平台抽奖程序
Unbelievabletobe10 分钟前
免费外汇api的响应时间在不同时段下的波动分析
大数据·开发语言·前端·python
大哥,带带弟弟19 分钟前
Grafana 前端嵌入与 JWT 鉴权实战
前端·grafana
小小小小宇20 分钟前
前端 V8 引擎垃圾回收机制与内存问题排查
前端
前端老石人31 分钟前
CSS 值定义语法
前端·css
sheeta199842 分钟前
Vue 前端基础笔记
前端·vue.js·笔记
小小小小宇42 分钟前
GitLab + GitLab Runner + Qiankun 微前端 + Nginx + Node 中间件 前端开发机从零搭建 CI/CD 全流程
前端
前端那点事1 小时前
别再写垃圾组件!Vue3 如何设计「真正可复用」的高质量通用组件
前端·vue.js