diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index 2b8f0605c..a044d8cc0 100644 --- a/src/content/reference/react/useContext.md +++ b/src/content/reference/react/useContext.md @@ -4,7 +4,7 @@ title: useContext -`useContext` is a React Hook that lets you read and subscribe to [context](/learn/passing-data-deeply-with-context) from your component. +`useContext` -- это хук, который позволяет вам считывать и подписываться на [контекст](/learn/passing-data-deeply-with-context) внутри вашего компонента. ```js const value = useContext(SomeContext) @@ -16,11 +16,11 @@ const value = useContext(SomeContext) --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `useContext(SomeContext)` {/*usecontext*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Вызовите `useContext` на верхнем уровне вашего компонента, чтобы прочитать и подписаться на [контекст.](/learn/passing-data-deeply-with-context) ```js import { useContext } from 'react'; @@ -30,30 +30,30 @@ function MyComponent() { // ... ``` -[See more examples below.](#usage) +[Больше примеров ниже.](#usage) -#### Parameters {/*parameters*/} +#### Параметры {/*parameters*/} -* `SomeContext`: The context that you've previously created with [`createContext`](/reference/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components. +* `SomeContext`: Контекст, который вы создали заранее с помощью [`createContext`](/reference/react/createContext). Сам по себе контекст не хранит данные. Он является представлением типа данных, которые вы можете предоставить или прочитать внутри ваших компонентов. -#### Returns {/*returns*/} +#### Возвращаемое значение {/*returns*/} -`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes. +`useContext` возвращает значение контекста для вызывающего компонента. Оно определяется как `value`, переданное ближайшему `SomeContext.Provider` выше по дереву, чем вызывающий компонент. Если такого источника нет, то вернётся `defaultValue`, который вы передали в [`createContext`](/reference/react/createContext) для этого контекста. Возвращаемое значение всегда актуально. React автоматически повторно рендерит компоненты, которые считывают определённый контекст, при его изменении. -#### Caveats {/*caveats*/} +#### Замечания {/*caveats*/} -* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `` **needs to be *above*** the component doing the `useContext()` call. -* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/reference/react/memo) does not prevent the children receiving fresh context values. -* If your build system produces duplicates modules in the output (which can happen with symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison. +* Вызов `useContext()` из компонента не будет затронут источниками, возвращёнными из *того же* компонента. Соответствующий `` **обязан быть *выше по дереву***, чем компонент, который вызывает `useContext()`. +* React **автоматически повторно рендерит** все дочерние компоненты, использующие источник, значение `value` которого было изменено. Предшествующее и следующее значения сравниваются, используя сравнение [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Пропуск повторных рендеров с помощью [`memo`](/reference/react/memo) не препятствует получению дочерними компонентами актуальных значений контекста. +* Если ваша система сборки дублирует выходящие модули (что может произойти при использовании символических ссылок), результат использования контекста может быть непредсказуемым. Передача чего-либо через контекст будет успешна, только если `SomeContext`, который вы используете для предоставления контекста, и `SomeContext`, который вы используете, чтобы его считать, ***полностью* идентичны друг другу**, аналогично оператору сравнения `===`. --- -## Usage {/*usage*/} +## Применение {/*usage*/} -### Passing data deeply into the tree {/*passing-data-deeply-into-the-tree*/} +### Передача данных вглубь дерева {/*passing-data-deeply-into-the-tree*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Вызовите `useContext` на верхнем уровне вашего компонента, чтобы прочитать и подписаться на [контекст.](/learn/passing-data-deeply-with-context) ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { useContext } from 'react'; @@ -63,9 +63,9 @@ function Button() { // ... ``` -`useContext` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. +`useContext` возвращает значение контекстадля переданного контекста. Чтобы определить значение контекста, React ищет в дереве компонентов **ближайший источник контекста выше по дереву** для данного конкретного контекста. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider: +Чтобы передать контекст компоненту `Button`, оберните его или один из его родительских компонентов в источник соответствующего контекста: ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -81,11 +81,11 @@ function Form() { } ``` -It doesn't matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `useContext(ThemeContext)`, it will receive `"dark"` as the value. +Не имеет значения, сколько слоёв компонентов находится между источником контекста и `Button`. Когда `Button` *в любом месте* внутри `Form` вызовет `useContext(ThemeContext)`, он получит значение `"dark"`. -`useContext()` always looks for the closest provider *above* the component that calls it. It searches upwards and **does not** consider providers in the component from which you're calling `useContext()`. +`useContext()` всегда ищет ближайший источник контекста *выше по дереву*, чем компонент, который его запрашивает. Он делает поиск только вверх и **не** рассматривает источники в компоненте, вызывающем `useContext()`. @@ -106,9 +106,9 @@ export default function MyApp() { function Form() { return ( - - - + + + ); } @@ -175,9 +175,9 @@ function Button({ children }) { --- -### Updating data passed via context {/*updating-data-passed-via-context*/} +### Изменение данных, передаваемых через контекст {/*updating-data-passed-via-context*/} -Often, you'll want the context to change over time. To update context, combine it with [state.](/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the context value to the provider. +Чаще всего вам понадобится, чтобы контекст менялся со временем. Чтобы изменить контекст, используйте его вместе с [состоянием.](/reference/react/useState) Объявите переменную состояния в родительском компоненте и передайте текущее состояние вниз по дереву как значение контекста. ```js {2} [[1, 4, "ThemeContext"], [2, 4, "theme"], [1, 11, "ThemeContext"]] function MyPage() { @@ -188,20 +188,20 @@ function MyPage() { ); } ``` -Now any `Button` inside of the provider will receive the current `theme` value. If you call `setTheme` to update the `theme` value that you pass to the provider, all `Button` components will re-render with the new `'light'` value. +Теперь любой компонент `Button` внутри источника будет получать текущее значение `theme`. Если вы вызовете `setTheme`, чтобы изменить значение `theme`, которое вы передаёте в источник, все компоненты `Button` будут повторно отрендерены с новым зачением `'light'`. - + -#### Updating a value via context {/*updating-a-value-via-context*/} +#### Изменение значения через контекст {/*updating-a-value-via-context*/} -In this example, the `MyApp` component holds a state variable which is then passed to the `ThemeContext` provider. Checking the "Dark mode" checkbox updates the state. Changing the provided value re-renders all the components using that context. +В этом примере компонент `MyApp` содержит переменную состояния, которая затем передаётся в источник `ThemeContext`. Активация чекбокса "Dark mode" изменяет состояние. Изменение предоставляемого значения вызывает повторный рендер всех компонентов, использующих данный контекст. @@ -223,7 +223,7 @@ export default function MyApp() { setTheme(e.target.checked ? 'dark' : 'light') }} /> - Use dark mode + Тёмная тема ) @@ -231,9 +231,9 @@ export default function MyApp() { function Form({ children }) { return ( - - - + + + ); } @@ -299,13 +299,13 @@ function Button({ children }) { -Note that `value="dark"` passes the `"dark"` string, but `value={theme}` passes the value of the JavaScript `theme` variable with [JSX curly braces.](/learn/javascript-in-jsx-with-curly-braces) Curly braces also let you pass context values that aren't strings. +Заметьте, что `value="dark"` передаёт строку `"dark"`, однако `value={theme}` передаёт значение JavaScript-переменной `theme`, используя [фигурные скобки JSX.](/learn/javascript-in-jsx-with-curly-braces) Фигурные скобки также позволяют вам передавать в контекст другие значения помимо строк. -#### Updating an object via context {/*updating-an-object-via-context*/} +#### Изменение объекта через контекст {/*updating-an-object-via-context*/} -In this example, there is a `currentUser` state variable which holds an object. You combine `{ currentUser, setCurrentUser }` into a single object and pass it down through the context inside the `value={}`. This lets any component below, such as `LoginButton`, read both `currentUser` and `setCurrentUser`, and then call `setCurrentUser` when needed. +В данном примере есть переменная состояния `currentUser`, которая хранит объект. Вы объединяете `{ currentUser, setCurrentUser }` в один объект и передаёте его вниз через контекст, используя `value={}`. В этом случае любой компонент ниже по дереву, например `LoginButton`, считывает и `currentUser`, и `setCurrentUser`, а затем вызывает `setCurrentUser` по необходимости. @@ -330,7 +330,7 @@ export default function MyApp() { function Form({ children }) { return ( - + ); @@ -343,13 +343,13 @@ function LoginButton() { } = useContext(CurrentUserContext); if (currentUser !== null) { - return

You logged in as {currentUser.name}.

; + return

Вы вошли как {currentUser.name}.

; } return ( + }}>Войти как Advika ); } @@ -395,9 +395,9 @@ label { -#### Multiple contexts {/*multiple-contexts*/} +#### Несколько контекстов {/*multiple-contexts*/} -In this example, there are two independent contexts. `ThemeContext` provides the current theme, which is a string, while `CurrentUserContext` holds the object representing the current user. +В данном примере есть два независимых контекста. `ThemeContext` передаёт текущую тему, которая является строкой, а `CurrentUserContext` хранит объект с описанием текущего пользователя. @@ -427,7 +427,7 @@ export default function MyApp() { setTheme(e.target.checked ? 'dark' : 'light') }} /> - Use dark mode + Использовать тёмную тему @@ -437,7 +437,7 @@ export default function MyApp() { function WelcomePanel({ children }) { const {currentUser} = useContext(CurrentUserContext); return ( - + {currentUser !== null ? : @@ -449,7 +449,7 @@ function WelcomePanel({ children }) { function Greeting() { const {currentUser} = useContext(CurrentUserContext); return ( -

You logged in as {currentUser.name}.

+

Вы вошли как {currentUser.name}.

) } @@ -461,7 +461,7 @@ function LoginForm() { return ( <> ); @@ -612,7 +612,7 @@ function MyProviders({ children, theme, setTheme }) { function WelcomePanel({ children }) { const {currentUser} = useContext(CurrentUserContext); return ( - + {currentUser !== null ? : @@ -624,7 +624,7 @@ function WelcomePanel({ children }) { function Greeting() { const {currentUser} = useContext(CurrentUserContext); return ( -

You logged in as {currentUser.name}.

+

Вы вошли как {currentUser.name}.

) } @@ -636,7 +636,7 @@ function LoginForm() { return ( <> ); @@ -947,25 +947,25 @@ ul, li { margin: 0; padding: 0; } --- -### Specifying a fallback default value {/*specifying-a-fallback-default-value*/} +### Указание запасного значения по умолчанию {/*specifying-a-fallback-default-value*/} -If React can't find any providers of that particular context in the parent tree, the context value returned by `useContext()` will be equal to the default value that you specified when you [created that context](/reference/react/createContext): +Если React не сможет найти ни одного источника конкретного контекста в дереве родительских компонентов, значение контекста возвращённое вызовом `useContext()` будет равно стандартному значению, которое вы указали при [создании этого контекста](/reference/react/createContext): ```js [[1, 1, "ThemeContext"], [3, 1, "null"]] const ThemeContext = createContext(null); ``` -The default value **never changes**. If you want to update context, use it with state as [described above.](#updating-data-passed-via-context) +Стандартное значения **остаётся неизменным**. Если вы хотите изменить контекст, используйте его вместе с состоянием, [как описано выше.](#updating-data-passed-via-context) -Often, instead of `null`, there is some more meaningful value you can use as a default, for example: +Зачастую, вместо использования `null`, можно задать более содержательное стандартное значение, например: ```js [[1, 1, "ThemeContext"], [3, 1, "light"]] const ThemeContext = createContext('light'); ``` -This way, if you accidentally render some component without a corresponding provider, it won't break. This also helps your components work well in a test environment without setting up a lot of providers in the tests. +В ином случае, если вы случайно отрендерите какой-то компонент без соответствующего источника контекста, что-то может пойти не так. Такой подход также поможет вашим компонентам хорошо работать в тестовом окружении, без установки множества источников в тестах. -In the example below, the "Toggle theme" button is always light because it's **outside any theme context provider** and the default context theme value is `'light'`. Try editing the default theme to be `'dark'`. +В примере ниже кнопка "Переключить тему" всегда светлая, потому что она находится **снаружи какого-либо источника контекста темы**, а стандартное значение источника контекста темы -- `'light'`. Можете попробовать изменить стандартное значение темы на `'dark'`. @@ -984,7 +984,7 @@ export default function MyApp() { ) @@ -992,9 +992,9 @@ export default function MyApp() { function Form({ children }) { return ( - - - + + + ); } @@ -1062,9 +1062,9 @@ function Button({ children, onClick }) { --- -### Overriding context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/} +### Переопределение контекста для части дерева {/*overriding-context-for-a-part-of-the-tree*/} -You can override the context for a part of the tree by wrapping that part in a provider with a different value. +Вы можете переопределить контекст для части дерева, обернув её в источник контекста с другим значением. ```js {3,5} @@ -1076,13 +1076,13 @@ You can override the context for a part of the tree by wrapping that part in a p ``` -You can nest and override providers as many times as you need. +Вы можете вкладывать и переопределять источники сколько вам нужно. - + -#### Overriding a theme {/*overriding-a-theme*/} +#### Переопределение темы {/*overriding-a-theme*/} -Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`). +В данном случае, кнопка *внутри* компонента `Footer` получает значение контекста (`"light"`), в отличие от кнопок снаружи, которые получают (`"dark"`). @@ -1101,9 +1101,9 @@ export default function MyApp() { function Form() { return ( - - - + + +