Here is my MWE in the case where our main component FooPage has 2 subcomponents FooButton and FooText, so, in this case, we have 8 files in total:
File #1: define the type of Значение контекста. < /p>
Код: Выделить всё
// types.ts
// define the type of the value provided by the context,
// it depends on which stuff we want to provide to the subcomponents
export type FooContextType = {
foo: number;
setFoo: React.Dispatch;
};
< /code>
Файл № 2: фактический внешний компонент, который мы будем использовать на нашей веб-странице.// FooPageWrapper.tsx
// This component is the one we actually use, it wraps
// the FooPage inside the context provider.
import FooProvider from "./context/FooProvider";
import FooPage from "./FooPage";
export default function FooPageWrapper() {
return (
);
}
< /code>
Файл № 3: фактический контент (который необходимо обернуть в поставщику контекста). < /p>
// FooPage.tsx
// This component is the one with the actual content.
// It must be used inside the context provider FooProvider.
import FooButton from "./components/FooButton";
import FooText from "./components/FooText";
export default function FooPage() {
return (
Foo Page
);
}
< /code>
Файл № 4: определение самого контекста.// context/FooContext.tsx
// defines the context.
import { createContext } from "react";
import { FooContextType } from "../types";
export const FooContext = createContext(undefined);
< /code>
Файл № 5: Поставщик контекста, в котором мы поместим всю нашу логику (это самая важная). < /p>
// context/FooProvider.tsx
// This is the actual context provider component.
// Here we provide the context value using useState,
// but we could provide a more complex value if needed,
// using useReducer or other state management solutions.
import { useState } from "react";
import { FooContext } from "./FooContext";
export default function FooProvider({
children,
}: {
children: React.ReactNode;
}) {
const [foo, setFoo] = useState(0);
return (
{children}
);
}
< /code>
Файл № 6: Пользовательский крючок, чтобы легко получить доступ к значению контекста в наших подкомпонентах.// context/useFoo.tsx
// Custom hook to use the context FooContext
// when we are in a component that is wrapped by the FooProvider.
import { useContext } from "react";
import { FooContext } from "./FooContext";
export default function useFoo() {
const c = useContext(FooContext);
if (c === undefined) {
throw new Error("FooContext is undefined");
}
return c;
}
< /code>
Файл #7: первый подкомпонент, который использует контекст.// components/FooButton.tsx
// Example of a component that uses the context FooContext
// (via the custom hook useFoo).
import useFoo from "../context/useFoo";
export default function FooButton() {
const { foo, setFoo } = useFoo();
return (
setFoo(foo + 1)}>
Foo is {foo}, click to increment it!
);
}
< /code>
Файл #8: второй подкомпонент, который использует контекст.// components/FooText.tsx
// Example of a component that uses the context FooContext
// (via the custom hook useFoo).
import useFoo from "../context/useFoo";
export default function FooText() {
const { foo } = useFoo();
return (
Foo is {foo}, this is a text component that uses the Foo context!
);
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ext-values
Мобильная версия