引言
在 React 应用中,状态管理是一个常见的需求。React 提供了多种方式来管理状态,其中 useContext
是一种简单且高效的方式,特别适用于全局状态的管理。本文将通过一个具体的例子——实现主题切换功能,来详细介绍如何使用 useContext
。
项目结构
我们的项目结构如下:
src/
├── App.tsx
└── components/
└── useContext/
├── Child.tsx
├── Parent.tsx
├── Test.tsx
└── ThemeContext.tsx
创建上下文
首先,我们需要创建一个上下文(Context),用于在整个应用中共享主题状态和更新主题的方法。
ThemeContext.tsx
// src/components/useContext/ThemeContext.tsx
import {
createContext, useContext, useState } from 'react';
interface ThemeContextType {
theme: string;
setTheme: (theme: string) => void;
}
export const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeContext.Provider');
}
return context;