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

React学习之useContext

具有树状结构关系组件之间传参可使用useContext进行跨组件之间进行传参

1、parent组件

import { useState } from "react"; import { Child } from "./Child"; import { ThemeContext } from "./UseContext"; export const UseContext = () => { //定义一个修改主题的函数 const [theme, setTheme] = useState<string>("light"); //定义一个切换主题的函数 const toggleTheme = () => { setTheme(theme === "light" ? "dark" : "light"); }; //定义需要传送的信息 const props = { name: "张三", age: 0 }; return ( <div> <p>{theme}</p> <ThemeContext.Provider value={{ theme, toggleTheme, props }}> <Child /> <button onClick={toggleTheme}>切换主题</button> </ThemeContext.Provider> </div> ); };

2、child组件

import {GrandChild} from './GrandChild' import { useContext } from 'react'; export const Child = () => { console.log('子组件') return ( <div> <p>子组件---</p> <GrandChild></GrandChild> </div> ); };

3、GrandChil组件

import { UseTheme } from "./useTheme"; export const GrandChild = () => { //引入自定义hook const { theme, toggleTheme, props } = UseTheme(); const toggleTheme2 = () => { //更改主题的方法 toggleTheme(); }; return ( <div> <p>传递的值----{theme}</p> <p> {props.name}---{props.age || 999} </p> <button onClick={toggleTheme2}>切换主题---通过改变顶层级数据</button> </div> ); };

4、UseContext组件

import { createContext } from "react"; export const ThemeContext = createContext({ theme: "light", toggleTheme: () => {}, // 默认空函数,避免消费时报错 props: { name: "", age: 0 }, });

5、useTheme组件(可把GrandChild组件内的获取数据方法单写成一个hook,实现功能抽离)

import { useContext } from "react"; import { ThemeContext } from "./UseContext"; export const UseTheme = () => { const { theme, toggleTheme, props } = useContext(ThemeContext); return { theme, toggleTheme, props }; };
http://www.jsqmd.com/news/270146/

相关文章:

  • 4位量化压缩Qwen3-0.6B,模型体积缩小75%仍可用
  • Dify开发实战:从零基础到项目实战
  • 别把希望交给魔法:一份清醒的健康指南
  • USB-Serial Controller D驱动下载前的设备识别方法
  • 三菱FX3U 16仓位配方程序开发记录
  • Scarab模组管理器:新手玩家如何3步解决空洞骑士模组安装难题
  • 实战Java微信小程序商城:一套代码玩转多端SaaS架构
  • Qwen All-in-One实战:情感分析与智能对话一体化解决方案
  • Unity游戏多语言本地化终极指南:XUnity.AutoTranslator完全解析
  • 基于形态学的权重自适应图像去噪:MATLAB数字图像处理探索
  • 组态王条件触发数据记录,记录数据后,条件触发存储到excel表格,存储文件名为出发时的年月日时分秒
  • 电动汽车Simulink仿真模型的奇妙世界
  • Modbus TCP转RTU串口通讯:基于Arduino的源码及资料包
  • 想让AI声音更像人?试试这个基于CosyVoice2的二次开发项目
  • Elasticsearch客户端工具自动化运维脚本应用实例
  • 基于卡尔曼滤波的语音处理:让语音重归纯净
  • 闭环步进电机设计资料分享[特殊字符]
  • 三菱FX5U PLC在4轴伺服机器人控制系统中的应用
  • 基于模型预测的三相整流器MATLAB仿真模型研究
  • 机器学习 - 自动化工作流
  • Z-Image-Turbo调优实践:提升出图质量的几个技巧
  • 当虚拟实训照进课堂:新能源汽车教学而生的动力总成拆装与检测软件
  • Comsol 流固耦合:探究球在流体中的运动轨迹
  • Emotion2Vec+ Large是否适合儿童语音?年龄适应性实测报告
  • Unity游戏自动翻译终极解决方案:XUnity.AutoTranslator深度解析
  • S7-200自由口协议实现英威腾GD200变频器控制与数据读取
  • 联想小新平板2025重装系统教程(TB373FU)
  • Qwen3-1.7B本地部署痛点解决:免配置镜像实战推荐
  • 【译】为什么构建人工智能代理大多是在浪费时间
  • 5分钟上手!用Cute_Animal_For_Kids_Qwen_Image生成儿童专属可爱动物图片