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

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)

        见后续文章

http://www.xdnf.cn/news/1494.html

相关文章:

  • 【网络原理】从零开始深入理解TCP的各项特性和机制.(一)
  • 机器学习漏洞大汇总——利用机器学习服务
  • Scrapy框架爬虫官网的学习
  • 放爱心烟花
  • # 构建和训练一个简单的CBOW词嵌入模型
  • GCoNet+:更强大的团队协作 Co-Salient 目标检测器 2023 GCoNet+(总结)
  • 【Deepseek学习大模型推理】MOONCAKE: A KVCache-centric Architecture调度(中)调度
  • win10 快速搭建 lnmp+swoole 环境 ,部署laravel6 与 swoole框架laravel-s项目3
  • 代码随想录算法训练营第二十五天
  • 卡方检验(Chi-square test)
  • 奇安信春招面试题
  • 在线测试来料公差
  • Java工厂模式解析:三种实现与最佳实践
  • 03-Java入门-JDK的安装和下载
  • 【KWDB 创作者计划】_上位机知识篇---PlatformIO
  • 用 Firebase 和 WebRTC 快速搭建一款浏览器视频聊天应用
  • 布布のC语言课堂——第一讲:揭开C语言的神秘面纱
  • 【KWDB 创作者计划】_深度学习篇---归一化反归一化
  • QtDesigner入门
  • bert4keras
  • mybatis框架补充
  • Spring JDBC 的开发步骤(非注解方式)
  • HashedWheelTimer源码分析
  • 网络安全中Base64编码到后端是何解了
  • 图解Mysql原理:深入理解事务的特性以及它的实现机制
  • IDEA设置手动代理,用户名密码被加密无法通过代码修改的解决方案
  • 4082P 信号/频谱分析仪
  • Javase 基础入门 —— 03 面向对象编程
  • (三)垂直分库架构、分布式数据库
  • MySQL 锁机制