当前位置: 首页 > news >正文

React-组件通信

1、父子组件通信

(1)父传子(props 传值)

// 父组件
function App() {const name = '张三'return (<div className="App"><Son name={name} /></div>);
}// 子组件
function Son(props) {return (<div>{ props.name }</div>)
}

(2)子传父(回调函数)

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {console.log(data)setMsg(data)}return (<div className="App"><div>{ msg }</div><Son onGetMsg={getMsg} /></div>);
}// 子组件
function Son({ onGetMsg }) {return (<div><button onClick={() => onGetMsg('子组件给父组件的数据')}>发送数据</button></div>)
}

(3)双向数据绑定

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {console.log(data);setMsg(data)}return (<div className="App"><div>{ msg }</div><Son msg={msg} onGetMsg={getMsg} /></div>);
}// 子组件
function Son({ msg, onGetMsg }) {return (<div><input type="text" value={msg} onChange={(e) => onGetMsg(e.target.value)} /></div>)
}

2、兄弟组件通信

        通过状态提升实现兄弟组件之间传值,子传父 => 父传子

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {setMsg(data)}return (<div className="App">this is App<A onGetMsg={getMsg} /><B msg={msg} /></div>);
}// 子组件A
function A({ onGetMsg }) {return (<div>this is A component<button onClick={() => onGetMsg('AAA')}>send</button></div>)
}// 子组件B
function B(props) {return (<div>this is B component{ props.msg }</div>)
}

3、跨层级组件通信

  1. 使用createContext创建上下文对象
  2. 在顶层组件(App)中使用Ctx.Provider组件提供数据
  3. 在底层组件(B)中通过useContext获取消费数据
import { createContext, useContext } from 'react';// 1.使用createContext创建上下文对象
const MsgContent = createContext();// 父组件
function App() {const msg = '哈哈哈';return (<div className="App">{/* 2.在顶层组件(App)中使用Ctx.Provider组件提供数据 */}<MsgContent.Provider value={msg}>this is App<A /></MsgContent.Provider></div>);
}// 子组件A
function A() {return (<div>this is A component<B /></div>)
}// 孙子组件B
function B() {// 3.在底层组件(B)中通过useContext获取消费数据const msg = useContext(MsgContent);return (<div>this is B component{msg}</div>)
}

4、任意组件通信(Redux/Zustand)

        见后续文章

相关文章:

  • 【高中数学/古典概率】4红2黑六选二,求取出两次都是红球的概率
  • AI在论文评审中的应用与工具推荐
  • WASM与Kotlin反编译难度对比分析
  • NVIDIA自动驾驶安全与技术读后感
  • 【低配置电脑预训练minimind的实践】
  • 关于 xpath 查找 XML 元素的一点总结
  • go.mod介绍
  • ‌RISC-V低功耗MCU动态时钟门控技术详解
  • CSS基础
  • 第二章、安全认证
  • Nginx 二进制部署与 Docker 部署深度对比
  • 学习海康VisionMaster之顶点检测
  • 03_JavaScript
  • 云网络与SASE架构:构建下一代企业安全网络
  • 悟空统计在SEO优化中的核心作用:外链质量评估
  • 人脸识别考勤系统实现教程:基于Face-Recognition、OpenCV与SQLite
  • Python-基础语法部分的20道题
  • 大文件上传Demo及面试要点
  • 目标检测篇---faster R-CNN
  • Redis中的hash数据结构设置过期时间的坑!!!
  • 老人误操作免密支付买几百只鸡崽,经济日报:支付要便捷也要安全
  • 首次面向上海、江苏招收本科生,西湖大学接连发布招生简章
  • 港股5月迎开门红,恒生科指涨3%,欧股开盘全线上扬
  • 韩国经济副总理崔相穆宣布辞职
  • 2025财政观察①长三角罚没收入增速放缓,24城仍在上涨
  • “网约摩托”在部分县城上线:起步价五六元,专家建议纳入监管