在React中使用Provider

首先

如题所示,我们将在React中使用Provider。

产物

スクリーンショット 2023-11-29 11.57.04.png

设计 (shè jì)

IMG_0827.jpeg

・在父组件以下,可以更新选项卡的信息。
・在子组件的标题部分,可以更新选项卡的信息。
・在子组件的内容部分,可以获取选项卡的信息并进行切换显示。

源代码

import { Content } from "./Content";
import { Header } from "./Header";
import { TabProvider } from "./TabContext";

const App: React.FC = () => {
  return (
    <TabProvider>
      <Header />
      <Content />
    </TabProvider>
  );
};

export default App;

import React, { useState, createContext, useContext, ReactNode } from "react";

export interface TabContextType {
  activeTab: number;
  setActiveTab: (index: number) => void;
}

export const TabContext = createContext<TabContextType | undefined>(undefined);

export interface TabProviderProps {
  children: ReactNode;
}

export const TabProvider: React.FC<TabProviderProps> = ({ children }) => {
  const [activeTab, setActiveTab] = useState(0);

  return (
    <TabContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabContext.Provider>
  );
};
import { useContext } from "react";
import { TabContext } from "./TabContext";

const TABS = ["Tab1", "Tab2", "Tab3", "Tab4"];

export const Header: React.FC = () => {
  const context = useContext(TabContext);
  if (!context) {
    throw new Error("Header must be used within a TabProvider");
  }
  const { activeTab, setActiveTab } = context;

  return (
    <div>
      {TABS.map((tab, index) => (
        <button key={index} onClick={() => setActiveTab(index)}>
          {tab}
        </button>
      ))}
    </div>
  );
};

import { useContext } from "react";
import { TabContext } from "./TabContext";

export const Content: React.FC = () => {
  const context = useContext(TabContext);
  if (!context) {
    throw new Error("Content must be used within a TabProvider");
  }
  const { activeTab } = context;

  return (
    <div>
      {activeTab === 0 && <div>Content for Tab 1</div>}
      {activeTab === 1 && <div>Content for Tab 2</div>}
      {activeTab === 2 && <div>Content for Tab 3</div>}
      {activeTab === 3 && <div>Content for Tab 4</div>}
    </div>
  );
};

广告
将在 10 秒后关闭
bannerAds