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

关于 React 19 的四种组件通信方法

注意:使用的是UI库是 antd-mobile

1.父子级组件通信

  • 父组件
  • 单向数据流:数据从父组件流向子组件。
  • 支持多种数据类型:字符串、数字、对象、数组、函数等。
  • 只读性:子组件不能直接修改 props 中的数据。
import { useState } from 'react'
import YdNavbar1 from './components/Ydnavbar1'
function App() {const [right, setRight] = useState('操作')const handleDataFromChild = (data) => {setRight(data)}return (<><YdNavbar1 rightMsg={right} onSendData={handleDataFromChild}></YdNavbar1></>)
}export default App
  • 子组件
  • 子组件通过props接收父组件传递的函数,然后调用该函数并传递参数给父组件
  • 反向通信:通过回调函数实现子组件向父组件传递数据。
  • 事件驱动:通常与 onClick、onChange 等事件结合使用。
import '../App.css'
import { Toast, Space, NavBar } from 'antd-mobile'// 父传子:子组件通过props接收父组件传参(rightMsg)
const YdNavbar1 = ({ rightMsg, onSendData }) => {// 子传父:子组件通过props接收父组件传递的函数(onSendData),然后调用该函数并传递参数给父组件const handleClick = () => {Toast.show({content: '提示',afterClose: () => {onSendData('儿子的问候')},})}return (<><div className="App"><Space style={{ width: '100vw' }} direction="vertical"><NavBar right={rightMsg} onBack={handleClick}>导航栏</NavBar></Space></div></>)
}export default YdNavbar1

2.通过Ref调用子组件方法

  • 父组件
  • 使用 useRef(父组件调用子组件方法)
  • 直接调用子组件方法:适用于需要父组件控制子组件行为的场景。
import { useState } from 'react'
import YdNavbar2 from './components/Ydnavbar2'
// 使用 useRef(父组件调用子组件方法)
import { useRef } from 'react'
function App() {const childRef = useRef(null)const callChildMethod = () => {childRef.current.sayHello()}return (<><YdNavbar2 ref={childRef}></YdNavbar2></>)
}export default App
  • 子组件
  • 需显式暴露方法:子组件必须通过 useImperativeHandle 暴露方法。
import '../App.css'
import { Space, NavBar } from 'antd-mobile'
import { useImperativeHandle, forwardRef } from 'react'
// props 是必须的:当使用 forwardRef 时,组件的函数参数必须包含 props 和 ref,即使没有使用 props
// 通过 forwardRef 包裹组件
const YdNavbar2 = forwardRef((props, ref) => {// 使用 useImperativeHandle 暴露给父组件方法(sayHello)useImperativeHandle(ref, () => ({sayHello: () => {console.log('使用ref调用子组件方法')},}))return (<><div className="App"><Space style={{ width: '100vw' }} direction="vertical"><NavBar>导航栏</NavBar></Space></div></>)
})export default YdNavbar2

3.使用 Context API(跨层级共享数据)

  • 在src目录创建文件夹 contexts 创建 MyContext.js 文件,再创建 MyContextProvider.jsx 文件,如图

  • MyContext.js
import { createContext } from 'react'// 可以创建多个 Context 对象
const MyContext = createContext()export default MyContext
  • MyContextProvider.jsx
import { useState } from 'react'
import MyContext from './MyContext'function MyProvider({ children }) {const [leftMsg, setLeftMsg] = useState('左边')return (<MyContext.Provider value={{ leftMsg, setLeftMsg }}>{children}</MyContext.Provider>)
}
export default MyProvider
  • 组件1
import { useState } from 'react'
import YdNavbar3 from './components/Ydnavbar3'
// 使用 Context API(跨层级共享数据)
import MyProvider from './contexts/MyContextProvider'
function App() {return (<><MyProvider><YdNavbar3></YdNavbar3></MyProvider></>)
}export default App
  • 组件2
import '../App.css'
import { Toast, Space, NavBar } from 'antd-mobile'
// 使用 Context API(跨层级共享数据)
import { useContext } from 'react'
// 引用上下文对象
import MyContext from '../contexts/MyContext'const YdNavbar1 = () => {const { leftMsg, setLeftMsg } = useContext(MyContext)return (<><div className="App"><Space style={{ width: '100vw' }} direction="vertical"><NavBar left={leftMsg} onBack={() => setLeftMsg('哈哈哈')}>导航栏</NavBar></Space></div></>)
}export default YdNavbar1

4.使用 Zustand 状态管理

  • 首先安装 Zustand
npm i zustand
  • 在 src 下创建 stores 文件夹,创建文件 useStore.js 文件
// stores/userStore.js
import { create } from 'zustand'const useUserStore = create((set) => ({user: null, // 初始状态setUser: (user) => set({ user }), // 修改用户的方法
}))export default useUserStore
  • 组件使用方法
import { useState } from 'react'
import { Button, Space } from 'antd-mobile'
// 使用 Zustand 状态管理
import useUserStore from './stores/userStore'
function App() {const { user, setUser } = useUserStore() // 获取状态和方法return (<><div>{user}</div><Button onClick={() => (user ? setUser(null) : setUser('132456'))}>改变用户</Button></>)
}export default App

文章转载自:

http://oqAN2Wg2.wbyLy.cn
http://Vav8U0Bz.wbyLy.cn
http://qygvwyAR.wbyLy.cn
http://ROAxIrpy.wbyLy.cn
http://xfWhDJoh.wbyLy.cn
http://9EusHR88.wbyLy.cn
http://5oGexjPH.wbyLy.cn
http://VMw5tM9f.wbyLy.cn
http://M6haBVmZ.wbyLy.cn
http://8jQ8dWgt.wbyLy.cn
http://HMcipTg9.wbyLy.cn
http://4cWdxXrz.wbyLy.cn
http://jlgr25Rp.wbyLy.cn
http://8ugtiltu.wbyLy.cn
http://IMhcy4U8.wbyLy.cn
http://JbbnpfW8.wbyLy.cn
http://p98C3MfE.wbyLy.cn
http://CKrGo6sm.wbyLy.cn
http://jb09nhF7.wbyLy.cn
http://BSMmtBTt.wbyLy.cn
http://UzRuWuQf.wbyLy.cn
http://w5BY2kAh.wbyLy.cn
http://92xHNCSQ.wbyLy.cn
http://o0hqb8cu.wbyLy.cn
http://ZpR0wjIu.wbyLy.cn
http://HBneNoCB.wbyLy.cn
http://hOjMuJ4F.wbyLy.cn
http://EfH9VpFu.wbyLy.cn
http://gTnybdV8.wbyLy.cn
http://VeY47Or1.wbyLy.cn
http://www.dtcms.com/a/370110.html

相关文章:

  • Joplin-解决 Node.js 中 “digital envelope routines::unsupported“ 错误
  • [论文阅读] 软件工程 - 需求工程 | 2012-2019年移动应用需求工程研究趋势:需求分析成焦点,数据源却藏着大问题?
  • sensitive-word 敏感词性能提升14倍优化全过程 v0.28.0
  • 留数法分解有理分式
  • 基于FPGA的汉明码编解码器系统(论文+源码)
  • C++经典的数据结构与算法之经典算法思想:排序算法
  • 大恒-NF相机如何控制风扇
  • 01.单例模式基类模块
  • 数位DP -
  • kotlin - 2个Fragment实现左右显示,左边列表,右边详情,平板横、竖屏切换
  • 基于SpringBoot+Thymeleaf开发的实验室助理工作管理系统
  • 手写MyBatis第53弹: @Intercepts与@Signature注解的工作原理
  • 基于SpringBoot+JSP开发的潮鞋网络商城
  • docker run 命令,不接it选项,run一个centos没有显示在运行,而run一个nginx却可以呢?
  • 【C++框架#3】Etcd 安装使用
  • 洛谷 P3178 [HAOI2015] 树上操作-提高+/省选-
  • Java全栈开发工程师的面试实战:从基础到复杂场景的技术探索
  • 【Flask】测试平台开发,重构提测管理页面-第二十篇
  • ICPC 2023 Nanjing R L 题 Elevator
  • TensorFlow 面试题及详细答案 120道(101-110)-- 底层原理与扩展
  • 《sklearn机器学习——聚类性能指标》Davies-Bouldin Index (戴维斯-博尔丁指数)
  • 美团9-6:编程题
  • 深度学习--自然语言预处理--- Word2Vec
  • Nikto 漏洞扫描工具使用指南
  • Redis(46) 如何搭建Redis哨兵?
  • Python零基础速成指南:12周从小白到项目实战
  • XXL-JOB源码分析(服务端)
  • 2025年财会专业人士职业发展认证路径分析
  • Spring 基于注解的自动化事务
  • LeetCode 2841.几乎唯一子数组的最大和