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

React组件通信——context(提供者/消费者)

Context 是 React 提供的一种组件间通信方式,主要用于解决跨层级组件 props 传递的问题。它允许数据在组件树中"跨级"传递,无需显式地通过每一层 props 向下传递。

一、Context 核心概念

1. 基本组成

  • React.createContext:创建 Context 对象

  • Context.Provider:提供数据的组件

  • Context.Consumer 或 useContext:消费数据的组件

2. 工作原理

二、示例

创建 Context 文件(独立模块)

// contexts/ThemeContext.js
import { createContext } from 'react';// 1. 创建Context并导出
const ThemeContext = createContext('light'); // 默认值// 2. 导出Provider组件
export const ThemeProvider = ThemeContext.Provider;// 3. 直接导出Context对象
export default ThemeContext;

提供者文件

// App.js
import React, { useState } from "react";
import { ThemeProvider } from "./contexts/ThemeContext";
import ThemedButton from "./ThemeButton";function App() {const [theme, setTheme] = useState("dark");return (<ThemeProvider value={theme}><ThemedButton /><button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>切换主题</button></ThemeProvider>);
}export default App;

消费者文件

// ThemedButton.js
import React, { useContext } from "react";
import ThemeContext from "./contexts/ThemeContext";function ThemedButton() {// 方式一:使用从Context文件导入的同一个Context对象const theme = useContext(ThemeContext);return (<div><buttonstyle={{background: theme === "dark" ? "#333" : "#EEE",color: theme === "dark" ? "white" : "black",}}>当前主题: {theme}</button>{/* 方式二:适用于class组件 */}<ThemeContext.Consumer>{(theme) => {return (<buttonstyle={{background: theme === "dark" ? "#333" : "#EEE",color: theme === "dark" ? "white" : "black",}}>当前主题: {theme}</button>);}}</ThemeContext.Consumer></div>);
}export default ThemedButton;
http://www.xdnf.cn/news/14361.html

相关文章:

  • MySQL常用函数详解之字符串函数
  • nohz_full 参数对内核软硬锁检测机制的影响分析
  • 嵌入式学习笔记 - SH79F6441 堆栈栈顶可以是片上内部RAM(00H-FFH)的任意地址怎么理解
  • (91)课113:存储函数与存储过程的区别总结。
  • DP刷题练习(三)
  • Golang 解大整数乘法
  • Python Pillow 库详解文档
  • pythton 语言的独特语法
  • Axure应用交互设计:多种类型元件实现新增中继器数据
  • 【springcloud】快速搭建一套分布式服务springcloudalibaba(五)
  • Python爬虫实战:研究Mr. Queue相关技术
  • 【Java SE】类和对象(3)
  • Kafka源码P2-生产者缓冲区
  • 基于大模型预测缺铁性贫血的综合技术方案大纲
  • 记录一次 Oracle 表空间不足问题的解决过程
  • Linux进程间通信(上)
  • Proteus8.17-LCD12864液晶屏幕仿真模型
  • 华为OD机试-考勤信息-双指针(JAVA 2025B卷)
  • AI是什么?大模型、语料、训练、推理、机器学习、神经网络等专业名词如何关联
  • 基于docker的nocobase本地部署流程
  • CPU的异常处理
  • PC16550 UART接收中断处理完整示例代码
  • 134-135Elements-UI组件库
  • 03- 六自由度串联机械臂(ABB)动力学分析
  • SoftMax 函数
  • Unity基础-范围检测
  • Redis全面深入学习目录
  • 求数组中最长单调不降连续子数组的长度
  • stm32 f103c8t6仿真 串口收发测试
  • 用AI配合MCP快速生成n8n工作流