Какой самый краткий способ обеспечить и потреблять значения контекста? [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Какой самый краткий способ обеспечить и потреблять значения контекста? [закрыто]

Сообщение Anonymous »

Я ищу наиболее краткий путь, в React, чтобы обеспечить контекст компоненту (скажем, «страница») и все его подкомпоненты. На данный момент, наиболее краткий способ, который я нашел, включает 6 файлов (!), Плюс один файл на субкомпонент, которому нужен контекст. Use a new file to share constants or functions between components.

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!

);
}
Пример работает, как и ожидалось: мы получаем страницу с кнопкой и текстом, который может читать и записать значение foo в контексте. Тем не менее, это очень многослов.>

Подробнее здесь: https://stackoverflow.com/questions/796 ... ext-values
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»