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;

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

相关推荐
这里有鱼汤20 分钟前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
用户21411832636021 小时前
dify案例分享-免费玩转 AI 绘图!Dify 整合 Qwen-Image,文生图 图生图一步到位
前端
IT_陈寒1 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell8 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip8 小时前
Node.js 子进程:child_process
前端·javascript
excel11 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel12 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼14 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping14 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙15 小时前
[译] Composition in CSS
前端·css