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;

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

相关推荐
LegendNoTitle7 分钟前
计算机三级等级考试 网络技术 选择题考点详细梳理
服务器·前端·经验分享·笔记·php
@大迁世界23 分钟前
1.什么是 ReactJS?
前端·javascript·react.js·前端框架·ecmascript
BJ-Giser1 小时前
Cesium 基于EZ-Tree的植被效果
前端·可视化·cesium
王码码20352 小时前
Flutter for OpenHarmony:Flutter 三方库 algoliasearch 毫秒级云端搜索体验(云原生搜索引擎)
android·前端·git·flutter·搜索引擎·云原生·harmonyos
发现一只大呆瓜2 小时前
深入浅出 AST:解密 Vite、Babel编译的底层“黑盒”
前端·面试·vite
天天鸭2 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
发现一只大呆瓜3 小时前
前端模块化:CommonJS、AMD、ES Module三大规范全解析
前端·面试·vite
IT_陈寒3 小时前
一文搞懂JavaScript的核心概念
前端·人工智能·后端
IT_陈寒3 小时前
Java开发者必看!5个提升开发效率的隐藏技巧,你用过几个?
前端·人工智能·后端
前端Hardy3 小时前
Wails v3 正式发布:用 Go 写桌面应用,体积仅 12MB,性能飙升 40%!
前端·javascript·go