diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md index e81678c8e2..9fe02863fd 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -4,45 +4,45 @@ title: Passing Data Deeply with Context -Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. *Context* lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props. +Обычно вы передаете информацию из родительского компонента в дочерний через пропсы. Но передача пропсов может стать громоздкой и неудобной, если вам приходится передавать их через множество промежуточных компонентов, или если многим компонентам в вашем приложении нужна одна и та же информация. *Контекст* позволяет родительскому компоненту сделать некоторую информацию доступной любому компоненту в дереве ниже него — независимо от глубины — без явной передачи через пропсы. -- What "prop drilling" is -- How to replace repetitive prop passing with context -- Common use cases for context -- Common alternatives to context +- Что такое "проп-дриллинг" (prop drilling) +- Как заменить повторяющуюся передачу пропсов контекстом +- Распространенные сценарии использования контекста +- Распространенные альтернативы контексту -## The problem with passing props {/*the-problem-with-passing-props*/} +## Проблема передачи пропсов {/*the-problem-with-passing-props*/} -[Passing props](/learn/passing-props-to-a-component) is a great way to explicitly pipe data through your UI tree to the components that use it. +[Передача пропсов](/learn/passing-props-to-a-component) — отличный способ явно передавать данные через дерево вашего UI компонентам, которые их используют. -But passing props can become verbose and inconvenient when you need to pass some prop deeply through the tree, or if many components need the same prop. The nearest common ancestor could be far removed from the components that need data, and [lifting state up](/learn/sharing-state-between-components) that high can lead to a situation called "prop drilling". +Но передача пропсов может стать громоздкой и неудобной, когда вам нужно передать какой-то пропс глубоко через дерево, или если многим компонентам нужен один и тот же пропс. Ближайший общий предок может быть далеко от компонентов, которым нужны данные, а [подъем состояния вверх](/learn/sharing-state-between-components) на такую высоту может привести к ситуации, называемой "проп-дриллинг". - + -Lifting state up +Подъем состояния вверх - + -Prop drilling +Проп-дриллинг -Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's context feature, there is! +Не было бы здорово, если бы существовал способ "телепортировать" данные в компоненты дерева, которым они нужны, без передачи пропсов? С помощью функции контекста React это возможно! -## Context: an alternative to passing props {/*context-an-alternative-to-passing-props*/} +## Контекст: альтернатива передаче пропсов {/*context-an-alternative-to-passing-props*/} -Context lets a parent component provide data to the entire tree below it. There are many uses for context. Here is one example. Consider this `Heading` component that accepts a `level` for its size: +Контекст позволяет родительскому компоненту предоставлять данные всему дереву ниже него. Существует множество применений контекста. Вот один из примеров. Рассмотрим компонент `Heading`, который принимает `level` для определения размера: @@ -106,7 +106,7 @@ export default function Heading({ level, children }) { -Let's say you want multiple headings within the same `Section` to always have the same size: +Допустим, вы хотите, чтобы несколько заголовков в одном `Section` всегда имели одинаковый размер: @@ -180,7 +180,7 @@ export default function Heading({ level, children }) { -Currently, you pass the `level` prop to each `` separately: +В настоящее время вы передаете пропс `level` каждому `` отдельно: ```js
@@ -190,7 +190,7 @@ Currently, you pass the `level` prop to each `` separately:
``` -It would be nice if you could pass the `level` prop to the `
` component instead and remove it from the ``. This way you could enforce that all headings in the same section have the same size: +Было бы неплохо, если бы вы могли передать пропс `level` компоненту `
` вместо этого и убрать его из ``. Таким образом, вы могли бы гарантировать, что все заголовки в одном разделе имеют одинаковый размер: ```js
@@ -200,35 +200,35 @@ It would be nice if you could pass the `level` prop to the `
` component
``` -But how can the `` component know the level of its closest `
`? **That would require some way for a child to "ask" for data from somewhere above in the tree.** +Но как компонент `` может узнать уровень своего ближайшего `
`? **Для этого нужен способ, чтобы дочерний компонент мог "запросить" данные откуда-то выше в дереве.** -You can't do it with props alone. This is where context comes into play. You will do it in three steps: +С помощью одних только пропсов это не сделать. Здесь на помощь приходит контекст. Вы сделаете это в три шага: -1. **Create** a context. (You can call it `LevelContext`, since it's for the heading level.) -2. **Use** that context from the component that needs the data. (`Heading` will use `LevelContext`.) -3. **Provide** that context from the component that specifies the data. (`Section` will provide `LevelContext`.) +1. **Создайте** контекст. (Вы можете назвать его `LevelContext`, так как он предназначен для уровня заголовка.) +2. **Используйте** этот контекст из компонента, которому нужны данные. (`Heading` будет использовать `LevelContext`.) +3. **Предоставьте** этот контекст из компонента, который определяет данные. (`Section` будет предоставлять `LevelContext`.) -Context lets a parent--even a distant one!--provide some data to the entire tree inside of it. +Контекст позволяет родительскому компоненту — даже удаленному! — предоставлять данные всему дереву внутри него. - + -Using context in close children +Использование контекста в близких дочерних компонентах - + -Using context in distant children +Использование контекста в удаленных дочерних компонентах -### Step 1: Create the context {/*step-1-create-the-context*/} +### Шаг 1: Создайте контекст {/*step-1-create-the-context*/} -First, you need to create the context. You'll need to **export it from a file** so that your components can use it: +Сначала вам нужно создать контекст. Вам нужно будет **экспортировать его из файла**, чтобы ваши компоненты могли его использовать: @@ -308,18 +308,18 @@ export const LevelContext = createContext(1); -The only argument to `createContext` is the _default_ value. Here, `1` refers to the biggest heading level, but you could pass any kind of value (even an object). You will see the significance of the default value in the next step. +Единственный аргумент для `createContext` — это _значение по умолчанию_. Здесь `1` относится к самому большому уровню заголовка, но вы можете передать любое значение (даже объект). Вы увидите значение значения по умолчанию на следующем шаге. -### Step 2: Use the context {/*step-2-use-the-context*/} +### Шаг 2: Используйте контекст {/*step-2-use-the-context*/} -Import the `useContext` Hook from React and your context: +Импортируйте хук `useContext` из React и ваш контекст: ```js import { useContext } from 'react'; import { LevelContext } from './LevelContext.js'; ``` -Currently, the `Heading` component reads `level` from props: +В настоящее время компонент `Heading` читает `level` из пропсов: ```js export default function Heading({ level, children }) { @@ -327,7 +327,7 @@ export default function Heading({ level, children }) { } ``` -Instead, remove the `level` prop and read the value from the context you just imported, `LevelContext`: +Вместо этого удалите пропс `level` и прочитайте значение из только что импортированного контекста, `LevelContext`: ```js {2} export default function Heading({ children }) { @@ -336,9 +336,9 @@ export default function Heading({ children }) { } ``` -`useContext` is a Hook. Just like `useState` and `useReducer`, you can only call a Hook immediately inside a React component (not inside loops or conditions). **`useContext` tells React that the `Heading` component wants to read the `LevelContext`.** +`useContext` — это хук. Как и `useState` и `useReducer`, вы можете вызывать хук только непосредственно внутри React-компонента (не внутри циклов или условий). **`useContext` сообщает React, что компонент `Heading` хочет прочитать `LevelContext`.** -Now that the `Heading` component doesn't have a `level` prop, you don't need to pass the level prop to `Heading` in your JSX like this anymore: +Теперь, когда у компонента `Heading` нет пропса `level`, вам больше не нужно передавать пропс `level` в `Heading` в вашем JSX вот так: ```js
@@ -348,7 +348,7 @@ Now that the `Heading` component doesn't have a `level` prop, you don't need to
``` -Update the JSX so that it's the `Section` that receives it instead: +Обновите JSX так, чтобы вместо этого его получал `Section`: ```jsx
@@ -358,7 +358,7 @@ Update the JSX so that it's the `Section` that receives it instead:
``` -As a reminder, this is the markup that you were trying to get working: +Напоминаем, вот разметка, которую вы пытались заставить работать: @@ -442,13 +442,13 @@ export const LevelContext = createContext(1); -Notice this example doesn't quite work, yet! All the headings have the same size because **even though you're *using* the context, you have not *provided* it yet.** React doesn't know where to get it! +Обратите внимание, этот пример пока не совсем работает! Все заголовки имеют одинаковый размер, потому что **даже если вы *используете* контекст, вы еще не *предоставили* его.** React не знает, откуда его взять! -If you don't provide the context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `

`. Let's fix this problem by having each `Section` provide its own context. +Если вы не предоставите контекст, React будет использовать значение по умолчанию, которое вы указали на предыдущем шаге. В этом примере вы указали `1` в качестве аргумента `createContext`, поэтому `useContext(LevelContext)` возвращает `1`, устанавливая все эти заголовки в `

`. Давайте исправим эту проблему, заставив каждый `Section` предоставлять свой собственный контекст. -### Step 3: Provide the context {/*step-3-provide-the-context*/} +### Шаг 3: Предоставьте контекст {/*step-3-provide-the-context*/} -The `Section` component currently renders its children: +Компонент `Section` в настоящее время отображает свои дочерние элементы: ```js export default function Section({ children }) { @@ -460,430 +460,41 @@ export default function Section({ children }) { } ``` -**Wrap them with a context provider** to provide the `LevelContext` to them: +**Оберните их в про -```js {1,6,8} -import { LevelContext } from './LevelContext.js'; - -export default function Section({ level, children }) { - return ( -
- - {children} - -
- ); -} -``` - -This tells React: "if any component inside this `
` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it. - - - -```js -import Heading from './Heading.js'; -import Section from './Section.js'; - -export default function Page() { - return ( -
- Title -
- Heading - Heading - Heading -
- Sub-heading - Sub-heading - Sub-heading -
- Sub-sub-heading - Sub-sub-heading - Sub-sub-heading -
-
-
-
- ); -} -``` - -```js src/Section.js -import { LevelContext } from './LevelContext.js'; - -export default function Section({ level, children }) { - return ( -
- - {children} - -
- ); -} -``` - -```js src/Heading.js -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; - -export default function Heading({ children }) { - const level = useContext(LevelContext); - switch (level) { - case 1: - return

{children}

; - case 2: - return

{children}

; - case 3: - return

{children}

; - case 4: - return

{children}

; - case 5: - return
{children}
; - case 6: - return
{children}
; - default: - throw Error('Unknown level: ' + level); - } -} -``` - -```js src/LevelContext.js -import { createContext } from 'react'; - -export const LevelContext = createContext(1); -``` - -```css -.section { - padding: 10px; - margin: 5px; - border-radius: 5px; - border: 1px solid #aaa; -} -``` - -
- -It's the same result as the original code, but you did not need to pass the `level` prop to each `Heading` component! Instead, it "figures out" its heading level by asking the closest `Section` above: - -1. You pass a `level` prop to the `
`. -2. `Section` wraps its children into ``. -3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`. - -## Using and providing context from the same component {/*using-and-providing-context-from-the-same-component*/} - -Currently, you still have to specify each section's `level` manually: - -```js -export default function Page() { - return ( -
- ... -
- ... -
- ... -``` - -Since context lets you read information from a component above, each `Section` could read the `level` from the `Section` above, and pass `level + 1` down automatically. Here is how you could do it: - -```js src/Section.js {5,8} -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; - -export default function Section({ children }) { - const level = useContext(LevelContext); - return ( -
- - {children} - -
- ); -} -``` - -With this change, you don't need to pass the `level` prop *either* to the `
` or to the ``: - - - -```js -import Heading from './Heading.js'; -import Section from './Section.js'; - -export default function Page() { - return ( -
- Title -
- Heading - Heading - Heading -
- Sub-heading - Sub-heading - Sub-heading -
- Sub-sub-heading - Sub-sub-heading - Sub-sub-heading -
-
-
-
- ); -} -``` - -```js src/Section.js -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; - -export default function Section({ children }) { - const level = useContext(LevelContext); - return ( -
- - {children} - -
- ); -} -``` - -```js src/Heading.js -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; +## Варианты использования контекста {/*use-cases-for-context*/} -export default function Heading({ children }) { - const level = useContext(LevelContext); - switch (level) { - case 0: - throw Error('Heading must be inside a Section!'); - case 1: - return

{children}

; - case 2: - return

{children}

; - case 3: - return

{children}

; - case 4: - return

{children}

; - case 5: - return
{children}
; - case 6: - return
{children}
; - default: - throw Error('Unknown level: ' + level); - } -} -``` - -```js src/LevelContext.js -import { createContext } from 'react'; - -export const LevelContext = createContext(0); -``` - -```css -.section { - padding: 10px; - margin: 5px; - border-radius: 5px; - border: 1px solid #aaa; -} -``` - -
- -Now both `Heading` and `Section` read the `LevelContext` to figure out how "deep" they are. And the `Section` wraps its children into the `LevelContext` to specify that anything inside of it is at a "deeper" level. - - - -This example uses heading levels because they show visually how nested components can override context. But context is useful for many other use cases too. You can pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on. - - - -## Context passes through intermediate components {/*context-passes-through-intermediate-components*/} - -You can insert as many components as you like between the component that provides context and the one that uses it. This includes both built-in components like `
` and components you might build yourself. - -In this example, the same `Post` component (with a dashed border) is rendered at two different nesting levels. Notice that the `` inside of it gets its level automatically from the closest `
`: - - - -```js -import Heading from './Heading.js'; -import Section from './Section.js'; - -export default function ProfilePage() { - return ( -
- My Profile - - -
- ); -} - -function AllPosts() { - return ( -
- Posts - -
- ); -} - -function RecentPosts() { - return ( -
- Recent Posts - - -
- ); -} - -function Post({ title, body }) { - return ( -
- - {title} - -

{body}

-
- ); -} -``` - -```js src/Section.js -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; - -export default function Section({ children, isFancy }) { - const level = useContext(LevelContext); - return ( -
- - {children} - -
- ); -} -``` - -```js src/Heading.js -import { useContext } from 'react'; -import { LevelContext } from './LevelContext.js'; - -export default function Heading({ children }) { - const level = useContext(LevelContext); - switch (level) { - case 0: - throw Error('Heading must be inside a Section!'); - case 1: - return

{children}

; - case 2: - return

{children}

; - case 3: - return

{children}

; - case 4: - return

{children}

; - case 5: - return
{children}
; - case 6: - return
{children}
; - default: - throw Error('Unknown level: ' + level); - } -} -``` - -```js src/LevelContext.js -import { createContext } from 'react'; - -export const LevelContext = createContext(0); -``` - -```css -.section { - padding: 10px; - margin: 5px; - border-radius: 5px; - border: 1px solid #aaa; -} - -.fancy { - border: 4px dashed pink; -} -``` - -
- -You didn't do anything special for this to work. A `Section` specifies the context for the tree inside it, so you can insert a `` anywhere, and it will have the correct size. Try it in the sandbox above! - -**Context lets you write components that "adapt to their surroundings" and display themselves differently depending on _where_ (or, in other words, _in which context_) they are being rendered.** - -How context works might remind you of [CSS property inheritance.](https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance) In CSS, you can specify `color: blue` for a `
`, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with `color: green`. Similarly, in React, the only way to override some context coming from above is to wrap children into a context provider with a different value. - -In CSS, different properties like `color` and `background-color` don't override each other. You can set all `
`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other.** Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem. - -## Before you use context {/*before-you-use-context*/} - -Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.** - -Here's a few alternatives you should consider before using context: - -1. **Start by [passing props.](/learn/passing-props-to-a-component)** If your components are not trivial, it's not unusual to pass a dozen props down through a dozen components. It may feel like a slog, but it makes it very clear which components use which data! The person maintaining your code will be glad you've made the data flow explicit with props. -2. **Extract components and [pass JSX as `children`](/learn/passing-props-to-a-component#passing-jsx-as-children) to them.** If you pass some data through many layers of intermediate components that don't use that data (and only pass it further down), this often means that you forgot to extract some components along the way. For example, maybe you pass data props like `posts` to visual components that don't use them directly, like ``. Instead, make `Layout` take `children` as a prop, and render ``. This reduces the number of layers between the component specifying the data and the one that needs it. - -If neither of these approaches works well for you, consider context. - -## Use cases for context {/*use-cases-for-context*/} - -* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look. -* **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. -* **Routing:** Most routing solutions use context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too. -* **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle. +* **Тематизация:** Если ваше приложение позволяет пользователю изменять его внешний вид (например, тёмный режим), вы можете поместить `Context.Provider` в верхнюю часть приложения и использовать этот контекст в компонентах, которым нужно настроить свой внешний вид. +* **Текущая учётная запись:** Многим компонентам может потребоваться знать, какой пользователь вошёл в систему в данный момент. Помещение этой информации в контекст делает её удобной для чтения в любом месте дерева компонентов. Некоторые приложения также позволяют работать с несколькими учётными записями одновременно (например, чтобы оставить комментарий от имени другого пользователя). В таких случаях может быть удобно обернуть часть пользовательского интерфейса во вложенный `Provider` с другим значением текущей учётной записи. +* **Маршрутизация:** Большинство решений для маршрутизации используют контекст внутри себя для хранения текущего маршрута. Именно так каждая ссылка "знает", активна она или нет. Если вы создаёте собственный маршрутизатор, вам, возможно, тоже захочется это сделать. +* **Управление состоянием:** По мере роста вашего приложения вы можете обнаружить, что много состояния находится ближе к вершине дерева компонентов. Многим удалённым компонентам ниже может потребоваться изменить его. Часто [используют редюсер вместе с контекстом](/learn/scaling-up-with-reducer-and-context) для управления сложным состоянием и передачи его удалённым компонентам без особых усилий. -Context is not limited to static values. If you pass a different value on the next render, React will update all the components reading it below! This is why context is often used in combination with state. +Контекст не ограничивается статическими значениями. Если вы передадите другое значение при следующем рендеринге, React обновит все компоненты, которые его читают ниже! Именно поэтому контекст часто используется в сочетании с состоянием. -In general, if some information is needed by distant components in different parts of the tree, it's a good indication that context will help you. +В целом, если какая-либо информация требуется удалённым компонентам в разных частях дерева, это хороший признак того, что контекст вам поможет. -* Context lets a component provide some information to the entire tree below it. -* To pass context: - 1. Create and export it with `export const MyContext = createContext(defaultValue)`. - 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep. - 3. Wrap children into `` to provide it from a parent. -* Context passes through any components in the middle. -* Context lets you write components that "adapt to their surroundings". -* Before you use context, try passing props or passing JSX as `children`. +* Контекст позволяет компоненту предоставлять некоторую информацию всему дереву ниже него. +* Для передачи контекста: + 1. Создайте и экспортируйте его с помощью `export const MyContext = createContext(defaultValue)`. + 2. Передайте его в хук `useContext(MyContext)` для чтения в любом дочернем компоненте, независимо от его глубины. + 3. Оберните дочерние элементы в `` для предоставления его от родителя. +* Контекст передаётся через любые промежуточные компоненты. +* Контекст позволяет писать компоненты, которые "адаптируются к своему окружению". +* Прежде чем использовать контекст, попробуйте передать пропсы или JSX в качестве `children`. -#### Replace prop drilling with context {/*replace-prop-drilling-with-context*/} +#### Замените передачу пропсов через несколько уровней на контекст {/*replace-prop-drilling-with-context*/} -In this example, toggling the checkbox changes the `imageSize` prop passed to each ``. The checkbox state is held in the top-level `App` component, but each `` needs to be aware of it. +В этом примере переключение флажка изменяет пропс `imageSize`, передаваемый каждому ``. Состояние флажка хранится в компоненте верхнего уровня `App`, но каждый `` должен быть осведомлён о нём. -Currently, `App` passes `imageSize` to `List`, which passes it to each `Place`, which passes it to the `PlaceImage`. Remove the `imageSize` prop, and instead pass it from the `App` component directly to `PlaceImage`. +В настоящее время `App` передаёт `imageSize` в `List`, который передаёт его каждому `Place`, который передаёт его `PlaceImage`. Удалите пропс `imageSize` и вместо этого передайте его из компонента `App` напрямую в `PlaceImage`. -You can declare context in `Context.js`. +Вы можете объявить контекст в `Context.js`. @@ -975,7 +586,7 @@ export const places = [{ }, { id: 3, name: 'Selarón Staircase in Rio de Janeiro, Brazil', - description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people."', + description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people".', imageId: 'aeO3rpI' }, { id: 4, @@ -1020,9 +631,9 @@ li { -Remove `imageSize` prop from all the components. +Удалите пропс `imageSize` из всех компонентов. -Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`: +Создайте и экспортируйте `ImageSizeContext` из `Context.js`. Затем оберните `List` в `` для передачи значения вниз и используйте `useContext(ImageSizeContext)` для его чтения в `PlaceImage`: @@ -1157,8 +768,8 @@ li { -Note how components in the middle don't need to pass `imageSize` anymore. +Обратите внимание, как промежуточные компоненты больше не передают `imageSize`. - + \ No newline at end of file