当前位置: 首页 > 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数据结构设置过期时间的坑!!!
  • 潘功胜:一季度中国经济开局良好,金融市场展现出较强韧性
  • 中宣部版权管理局:微短剧出海面临版权交易不畅、海外维权较难等难题
  • 广州远洋宾馆负一层配电房发生火情:明火已扑灭,无人员伤亡
  • 国家新闻出版署:4月共118款国产网络游戏获批
  • A股低开高走,震荡收涨:两市成交10414亿元,4360股收涨
  • 语言天才、魔方大师,击败王楚钦前他豪言:我能比中国球员强