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

React Hooks useContext

开发环境是React Native + Taro + Typescript,下面第一部分是父组件

import React, { useState } from 'react'
import { View, Text } from '@tarojs/components'
import AppContext, { Theme, User } from './Components/ComContext'
import ContextA from './Components/ContextA'
import ContextB from './Components/ContextB'
import ContextC from './Components/ContextC'
import styles from './index.module.scss'
import {HKText,HKView
} from 'hk-components';const UseContext: React.FC = () => {const [theme, setTheme] = useState<Theme>(Theme.LIGHT)const [user, setUser] = useState<User>({ name: '小明', age: 18 })const toggleTheme = () => {// 使用函数式更新,确保类型安全setTheme(currentTheme => currentTheme === Theme.LIGHT ? Theme.DARK : Theme.LIGHT)}const updateUser = (newUser: User) => {setUser(newUser)}return (<AppContext.Provider value={{theme,toggleTheme,user,updateUser}}>{/* 注:如果在这个位置再多写一份AppContext.Provider,那么这个位置的provider的值会覆盖外层的,子组件也会获取覆盖后的值*/}<HKView className={styles.container}><Text className='title'>父组件</Text><Text>当前主题: {theme}</Text><Text>用户名: {user.name}</Text><Text>用户年龄: {user.age}</Text><View className={styles.showTextBox}><ContextA /><ContextB /></View><View><Text>在同一个子组件中,实现隔代组件间共享一份数据</Text><ContextC></ContextC></View></HKView></AppContext.Provider>)
}export default UseContext

下面的三部分为子组件:ContextA、ContextB、ContextC

import { View, Text, Button } from '@tarojs/components'
import AppContext from './ComContext'
import styles from './index.module.scss'
import {HKText,HKView
} from 'hk-components';const ContextA: React.FC = () => {const { theme, toggleTheme, user, updateUser } = useContext(AppContext)const handleIncreaseAge = () => {updateUser({ ...user, age: user.age + 1 })}return (<HKView className={styles.container}><View className={styles.showTextBox}><Text className={styles.showText}>ContextA 组件</Text><Text className={styles.showText}>当前主题: {theme}</Text><Text className={styles.showText}>用户名: {user.name}</Text><Text className={styles.showText}>用户年龄: {user.age}</Text></View><View className={styles.actionContainer}><Button className={styles.actionBox} onClick={toggleTheme}>切换主题</Button><Button className={styles.actionBox} onClick={handleIncreaseAge}>增加年龄</Button></View></HKView>)
}export default ContextA
import React, { useContext } from 'react'
import { View, Text, Button } from '@tarojs/components'
import AppContext from './ComContext'
import styles from  './index.module.scss'
import {HKText,HKView
} from 'hk-components';const ContextB: React.FC = () => {const { theme, toggleTheme, user, updateUser } = useContext(AppContext)const handleToggleUser = () => {const newName = user.name === '小明' ? '小红' : '小明'updateUser({ ...user, name: newName })}return (<HKView className={styles.container}><View className={styles.showTextBox}><Text className={styles.showText}>ContextB 组件</Text><Text className={styles.showText}>当前主题: {theme}</Text><Text className={styles.showText}>用户名: {user.name}</Text><Text className={styles.showText}>用户年龄: {user.age}</Text></View><View className={styles.actionContainer}><Button className={styles.actionBox} onClick={toggleTheme}>切换主题</Button><Button className={styles.actionBox} onClick={handleToggleUser}>切换用户</Button></View></HKView>)
}export default ContextB
import React, { createContext, useContext, useState } from 'react';
import { View, Text, Button } from '@tarojs/components';
import {HKText,HKView
} from 'hk-components';// 创建Context
const MyContext = createContext<any>(null);// ContextC 父组件
const ContextC: React.FC = () => {const [count, setCount] = useState(0);const updateCount = (newCount: number) => {setCount(newCount);};const contextValue = {message: 'Hello from Context!',count,updateCount,user: {name: '张三',age: 25}};return (<MyContext.Provider value={contextValue}><View style={{ padding: 20, backgroundColor: '#f5f5f5',minHeight: '100vh'}}><Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 16 }}>ContextC 父组件</Text><Text style={{ marginBottom: 16 }}>当前计数: {count}</Text><ComXa /></View></MyContext.Provider>);
};// ComXa 子组件
const ComXa: React.FC = () => {return (<View style={{ padding: 16, backgroundColor: '#e3f2fd', margin: 10, borderRadius: 8}}><Text style={{ fontSize: 16, marginBottom: 12 }}>ComXa 子组件</Text><ComXe /></View>);
};// ComXe 孙子组件(使用useContext)
const ComXe: React.FC = () => {const context = useContext(MyContext);if (!context) {return (<View><Text>Context未找到</Text></View>);}const { message, count, updateCount, user } = context;const handleIncrement = () => updateCount(count + 1);const handleDecrement = () => updateCount(count - 1);return (<View style={{ padding: 16, backgroundColor: '#fff3e0', borderRadius: 8}}><Text style={{ fontSize: 16, fontWeight: 'bold', marginBottom: 8 }}>ComXe 孙子组件</Text><Text style={{ marginBottom: 8 }}>消息: {message}</Text><Text style={{ marginBottom: 8 }}>用户: {user.name} ({user.age}岁)</Text><Text style={{ marginBottom: 12 }}>计数: {count}</Text><View style={{ flexDirection: 'row', gap: 8 }}><Button onClick={handleDecrement}>减少</Button><Button onClick={handleIncrement}>增加</Button></View></View>);
};export default ContextC;

下面为类型推断的一些声明与export

import { createContext } from 'react'// 使用枚举方式定义主题,避免类型推断问题
export enum Theme {LIGHT = 'light',DARK = 'dark'
}export interface User {name: stringage: number
}export interface AppContextValue {theme: ThemetoggleTheme: () => voiduser: UserupdateUser: (user: User) => void
}// 创建 Context
const AppContext = createContext<AppContextValue>({theme: Theme.LIGHT,toggleTheme: () => {},user: { name: '', age: 0 },updateUser: () => {}
})export default AppContext


文章转载自:

http://eOiMasrJ.qggcc.cn
http://z1b616v1.qggcc.cn
http://t7TPZ66E.qggcc.cn
http://nf3p2COh.qggcc.cn
http://5lL1V0R3.qggcc.cn
http://9nGXfyxq.qggcc.cn
http://iStgLLbx.qggcc.cn
http://7wXo12tG.qggcc.cn
http://l3eFXMVy.qggcc.cn
http://mbv1LHqp.qggcc.cn
http://tX4srE8u.qggcc.cn
http://Zl7kwYLe.qggcc.cn
http://jcvrXWzi.qggcc.cn
http://lMRb4J3V.qggcc.cn
http://xI8RcUIC.qggcc.cn
http://3LIRXTZZ.qggcc.cn
http://upygJo2Q.qggcc.cn
http://ka9VF9Yd.qggcc.cn
http://X1BTvS5P.qggcc.cn
http://D3Xb7pJv.qggcc.cn
http://D2HKGE0R.qggcc.cn
http://MO75wu0s.qggcc.cn
http://aSEuwMW9.qggcc.cn
http://eAXs4fHT.qggcc.cn
http://clxeLFB9.qggcc.cn
http://RD6e7kg4.qggcc.cn
http://SxvBIexY.qggcc.cn
http://Upi8dSL1.qggcc.cn
http://8RYA1Eox.qggcc.cn
http://PTCF7AI9.qggcc.cn
http://www.dtcms.com/a/368758.html

相关文章:

  • 【Linux】Linux 的 cp -a 命令的作用
  • 基于FPGA实现CRC校验码算法(以MODBUS中校验码要求为例)verilog代码+仿真验证
  • LeetCode刷题-top100( 矩阵置零)
  • 算法模板(Java版)_DFS与BFS
  • 一分钟了解Modbus 转 IEC61850 网关
  • Webpack 有哪些特性?构建速度?如何优化?
  • 2025精选5款AI视频转文字工具,高效转录秒变文字!
  • 【最新版】发烧级完美解码播放器PureCodec v2025.08.29 中文免费版_电脑播放器影音解码包
  • 阿里云国际代理:阿里云的云数据库是什么?
  • 盲盒抽卡机小程序功能版块设计的合理性评估维度
  • Memory write error at 0x100000. MMU page translation fault
  • 纯血鸿蒙开发入门:2.展示hello world
  • 【1】策略模式 + 模板方法模式的联合应用
  • 突发奇想,还未实践,在Vben5的Antd模式下,将表单从「JS 配置化」改写成「模板可视化」形式(豆包版)
  • Flash Attention:突破大模型推理内存瓶颈的革命性算法
  • 【正则表达式】 正则表达式的分组和引用
  • 具身智能的工程落地:视频-控制闭环的实践路径
  • E+H音叉开关FTL31-AA4M2AAWBJ
  • Android 权限机制默认授权分析
  • 深入理解 HarmonyOS Stage 模型与 UIAbility 生命周期管理
  • Vue3中的数据响应【4】
  • 因泰立科技:用激光雷达重塑智能工厂物流生态
  • 【Windows】通过 runas 命令实现多用户权限测试的完整流程
  • LangChain实战(十六):构建基于SQL数据库的数据分析Agent
  • Struts2 工作总结
  • 软件设计模式之单例模式
  • 小迪安全v2023学习笔记(七十八讲)—— 数据库安全RedisCouchDBH2database未授权CVE
  • 【Go】P2 Golang 常量与变量
  • Leetcode—721. 账户合并【中等】
  • Go初级之十:错误处理与程序健壮性