【useContext Hook】解决组件树层级较深时props逐级传递问题

引言

在 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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值