diff --git a/content/docs/context.md b/content/docs/context.md index 8e41a465f..d7ec53d80 100644 --- a/content/docs/context.md +++ b/content/docs/context.md @@ -1,60 +1,60 @@ --- id: context -title: Context +title: Контекст permalink: docs/context.html --- -Context provides a way to pass data through the component tree without having to pass props down manually at every level. +Контекст позволяет передавать данные через дерево компонентов без необходимости передавать пропсы на промежуточных уровнях. -In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree. +В типичном React приложении данные передаются сверху-вниз (от родителя к дочернему компоненту) с помощью пропсов. Однако, этот способ может быть череcчур громоздким для некоторых типов пропсов (например выбранный язык, UI-тема), которые необходимо передавать во многие компоненты в приложении. Контекст предоставляет способ делиться такими данными между компонентами без необходимости явно передавать пропсы через каждый уровень дерева. -- [When to Use Context](#when-to-use-context) -- [Before You Use Context](#before-you-use-context) +- [Когда использовать контекст](#when-to-use-context) +- [Перед тем, как вы начнёте использовать контекст](#before-you-use-context) - [API](#api) - [React.createContext](#reactcreatecontext) - [Context.Provider](#contextprovider) - [Class.contextType](#classcontexttype) - [Context.Consumer](#contextconsumer) -- [Examples](#examples) - - [Dynamic Context](#dynamic-context) - - [Updating Context from a Nested Component](#updating-context-from-a-nested-component) - - [Consuming Multiple Contexts](#consuming-multiple-contexts) -- [Caveats](#caveats) -- [Legacy API](#legacy-api) +- [Примеры](#examples) + - [Динамический контекст](#dynamic-context) + - [Изменение контекста из вложенного компонента](#updating-context-from-a-nested-component) + - [Использование нескольких контекстов](#consuming-multiple-contexts) +- [Предостережения](#caveats) +- [Устаревший API](#legacy-api) -## When to Use Context {#when-to-use-context} +## Когда использовать контекст {#when-to-use-context} -Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component: +Контекст разработан для передачи данных, которые можно назвать «глобальными» для всего дерева React-компонентов (например текущий аутентифицированный пользователь, UI-тема или выбранный язык). В примере ниже мы вручную передаём `theme` проп, чтобы стилизовать компонент Button: `embed:context/motivation-problem.js` -Using context, we can avoid passing props through intermediate elements: +Контекст позволяет избежать передачи пропсов в промежуточные компоненты: `embed:context/motivation-solution.js` -## Before You Use Context {#before-you-use-context} +## Перед тем, как вы начнёте использовать контекст {#before-you-use-context} -Context is primarily used when some data needs to be accessible by *many* components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. +Обычно контекст используется, если необходимо обеспечить доступ данных во *многих* компонентах на разных уровнях вложенности. По возможности не используйте его, так как это усложняет переиспользование компонентов. -**If you only want to avoid passing some props through many levels, [component composition](/docs/composition-vs-inheritance.html) is often a simpler solution than context.** +**Если вы хотите избавиться от передачи некоторых пропсов на множество уровней вниз, обычно [композиция компонентов](/docs/composition-vs-inheritance.html) является более простым решением, чем контекст.** -For example, consider a `Page` component that passes a `user` and `avatarSize` prop several levels down so that deeply nested `Link` and `Avatar` components can read it: +Например, давайте рассмотрим компонент `Page`, который передаёт пропсы `user` и `avatarSize` на несколько уровней вниз, чтобы глубоко вложенные компоненты `Link` и `Avatar` смогли их использовать: ```js -// ... which renders ... +// ... который рендерит ... -// ... which renders ... +// ... который рендерит ... -// ... which renders ... +// ... который рендерит ... ``` -It might feel redundant to pass down the `user` and `avatarSize` props through many levels if in the end only the `Avatar` component really needs it. It's also annoying that whenever the `Avatar` component needs more props from the top, you have to add them at all the intermediate levels too. +Передача пропсов `user` и `avatarSize` вниз выглядит избыточной, если в итоге их использует только компонент `Avatar`. Так же плохо, если компоненту `Avatar` вдруг потребуется больше пропсов сверху, тогда вам придётся добавить их на все промежуточные уровни. -One way to solve this issue **without context** is to [pass down the `Avatar` component itself](/docs/composition-vs-inheritance.html#containment) so that the intermediate components don't need to know about the `user` prop: +Один из способов решить эту проблему **без контекста** — [передать вниз сам компонент `Avatar`](/docs/composition-vs-inheritance.html#containment), в случае чего промежуточным компонентам не нужно знать о пропсах `user` и `avatarSize`: ```js function Page(props) { @@ -67,21 +67,21 @@ function Page(props) { return ; } -// Now, we have: - -// ... which renders ... +// Теперь, это выглядит так: + +// ... который рендерит ... -// ... which renders ... +// ... который рендерит ... -// ... which renders ... +// ... который рендерит ... {props.userLink} ``` -With this change, only the top-most Page component needs to know about the `Link` and `Avatar` components' use of `user` and `avatarSize`. +С этими изменениями, только корневой компонент `Page` знает о том, что компоненты `Link` и `Avatar` используют `user` и `avatarSize`. -This *inversion of control* can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components. However, this isn't the right choice in every case: moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want. +Этот способ может сделать ваш код чище во многих случаях, уменьшая количество пропсов, которые вы должны передавать через ваше приложение, и давая больше контроля корневым компонентам. Однако, это решение не является верным в каждом случае. Перемещая больше сложной логики вверх по дереву, вы перегружаете вышестоящие компоненты. -You're not limited to a single child for a component. You may pass multiple children, or even have multiple separate "slots" for children, [as documented here](/docs/composition-vs-inheritance.html#containment): +Вы не ограничены в передаче строго одного компонента. Вы можете передать несколько дочерних компонентов или, даже, создать для них разные «слоты», [как показано здесь](/docs/composition-vs-inheritance.html#containment): ```js function Page(props) { @@ -103,9 +103,9 @@ function Page(props) { } ``` -This pattern is sufficient for many cases when you need to decouple a child from its immediate parents. You can take it even further with [render props](/docs/render-props.html) if the child needs to communicate with the parent before rendering. +Этого паттерна достаточно для большинства случаев, когда вам необходимо отделить дочерний компонент от его промежуточных родителей. Вы можете пойти ещё дальше, используя [рендер-пропсы](/docs/render-props.html), если дочерним компонентам необходимо взаимодействовать с родителем перед рендером. -However, sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you "broadcast" such data, and changes to it, to all components below. Common examples where using context might be simpler than the alternatives include managing the current locale, theme, or a data cache. +Однако, иногда одни и те же данные должны быть доступны во многих компонентах на разных уровнях дерева и вложенности. Контекст позволяет распространить эти данные и их изменения на все компоненты ниже по дереву. Управление текущим языком, UI темой или кэшем данных — это пример тех случаев, когда реализация с помощью контекста будет проще использования альтернативных подходов. ## API {#api} @@ -115,9 +115,9 @@ However, sometimes the same data needs to be accessible by many components in th const MyContext = React.createContext(defaultValue); ``` -Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching `Provider` above it in the tree. +Создание объекта Context. Когда React рендерит компонент, который подписан на этот объект, React получит текущее значение контекста из ближайшего подходящего `Provider` выше в дереве компонентов. -The `defaultValue` argument is **only** used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing `undefined` as a Provider value does not cause consuming components to use `defaultValue`. +Аргумент `defaultValue` используется **только** в том случае, если для компонента нет подходящего `Provider` выше в дереве. Это может быть полезно для тестирования компонентов в изоляции без необходимости оборачивать их. Обратите внимание: если передать `undefined` в `value` у `Provider`, компоненты, использующие этот контекст, не будут использовать `defaultValue`. ### `Context.Provider` {#contextprovider} @@ -125,17 +125,17 @@ The `defaultValue` argument is **only** used when a component does not have a ma ``` -Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. +Каждый объект Контекста используется вместе с `Provider` компонентом, который позволяет дочерним компонентам, использующим этот контекст, подписаться на его изменения. -Accepts a `value` prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree. +Принимает проп `value`, который будут передан во все компоненты, использующие этот контекст и являющиеся потомками этого Provider компонента. Один Provider может быть связан с несколькими компонентами, потребляющими контекст. Так же Provider компоненты могут быть вложены друг в друга, переопределяя значение контекста глубже в дереве. -All consumers that are descendants of a Provider will re-render whenever the Provider's `value` prop changes. The propagation from Provider to its descendant consumers is not subject to the `shouldComponentUpdate` method, so the consumer is updated even when an ancestor component bails out of the update. +Все потребители, которые являются потомками Provider, будут повторно рендериться, как только проп `value` у Provider изменился. Потребитель перерендерится при изменении контекста, даже если его родитель, не использующий данный контекст, блокирует повторные рендеры с помощью `shouldComponentUpdate`. -Changes are determined by comparing the new and old values using the same algorithm as [`Object.is`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description). +Изменения определяются с помощью сравнения нового и старого значения, используя алгоритм, аналогичный [`Object.is`](//developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description). -> Note -> -> The way changes are determined can cause some issues when passing objects as `value`: see [Caveats](#caveats). +> Примечание +> +> Способ, по которому определяются изменения, может вызвать проблемы при передачи объекта в `value`: смотрите [Предостережения](#caveats). ### `Class.contextType` {#classcontexttype} @@ -143,7 +143,7 @@ Changes are determined by comparing the new and old values using the same algori class MyClass extends React.Component { componentDidMount() { let value = this.context; - /* perform a side-effect at mount using the value of MyContext */ + /* выполнить побочный эффект на этапе монтирования, используя значение MyContext */ } componentDidUpdate() { let value = this.context; @@ -155,19 +155,19 @@ class MyClass extends React.Component { } render() { let value = this.context; - /* render something based on the value of MyContext */ + /* отрендерить что-то, используя значение MyContext */ } } MyClass.contextType = MyContext; ``` -The `contextType` property on a class can be assigned a Context object created by [`React.createContext()`](#reactcreatecontext). This lets you consume the nearest current value of that Context type using `this.context`. You can reference this in any of the lifecycle methods including the render function. +В свойство класса `contextType` может быть назначен объект Контекста, созданный с помощью [`React.createContext()`](#reactcreatecontext). Это позволяет вам использовать ближайшее и актуальное значение указанного Контекста при помощи `this.context`. В этом случае вы получаете доступ к контексту, как во всех методах жизненного цикла, так и в рендер методе. -> Note: +> Примечание > -> You can only subscribe to a single context using this API. If you need to read more than one see [Consuming Multiple Contexts](#consuming-multiple-contexts). +> Вы можете подписаться только на один контекст, используя этот API. В случае, если вам необходимо использовать больше одного, смотрите [Использование нескольких контекстов](#consuming-multiple-contexts). > -> If you are using the experimental [public class fields syntax](https://babeljs.io/docs/plugins/transform-class-properties/), you can use a **static** class field to initialize your `contextType`. +> Если вы используете эксперементальный [синтаксис публичных полей класса](https://babeljs.io/docs/plugins/transform-class-properties/), вы можете использовать **static** поле класса, чтобы инициализировать ваш `contextType`. ```js @@ -175,7 +175,7 @@ class MyClass extends React.Component { static contextType = MyContext; render() { let value = this.context; - /* render something based on the value */ + /* отрендерить что-то, используя значение MyContext */ } } ``` @@ -184,23 +184,23 @@ class MyClass extends React.Component { ```js - {value => /* render something based on the context value */} + {value => /* отрендерить что-то, используя значение контекста */} ``` -A React component that subscribes to context changes. This lets you subscribe to a context within a [function component](/docs/components-and-props.html#function-and-class-components). +`Consumer` — это React-компонент, который подписывается на изменения контекста. В свою очередь, это позволяет вам подписаться на контекст в [функциональном компоненте](/docs/components-and-props.html#function-and-class-components). -Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. The `value` argument passed to the function will be equal to the `value` prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the `value` argument will be equal to the `defaultValue` that was passed to `createContext()`. +`Consumer` принимает [функцию в качестве дочернего компонента](/docs/render-props.html#using-props-other-than-render). Эта функция принимает текущее значение контекста и возвращает React-компонент. Передаваемый аргумент `value` будет равен ближайшему (вверх по дереву) значению этого контекста, а именно `value` пропу Provider компонента. Если такого Provider компонента не существует, `value` аргумент будет равен значению `defaultValue`, которое было передано в `createContext()`. -> Note -> -> For more information about the 'function as a child' pattern, see [render props](/docs/render-props.html). +> Примечание +> +> Подробнее про паттерн «_функция как дочерний компонент_» можно узнать на странице [Рендер-пропсы](/docs/render-props.html). -## Examples {#examples} +## Примеры {#examples} -### Dynamic Context {#dynamic-context} +### Динамический контекст {#dynamic-context} -A more complex example with dynamic values for the theme: +Более сложный пример динамических значений для UI темы: **theme-context.js** `embed:context/theme-detailed-theme-context.js` @@ -211,9 +211,9 @@ A more complex example with dynamic values for the theme: **app.js** `embed:context/theme-detailed-app.js` -### Updating Context from a Nested Component {#updating-context-from-a-nested-component} +### Изменение контекста из вложенного компонента {#updating-context-from-a-nested-component} -It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context: +Довольно часто необходимо изменить контекст из компонента, который находится где-то глубоко в дереве компонентов. В этом случае вы можете добавить в контекст функцию, которая позволит потребителям изменить значение этого контекста: **theme-context.js** `embed:context/updating-nested-context-context.js` @@ -224,28 +224,26 @@ It is often necessary to update the context from a component that is nested some **app.js** `embed:context/updating-nested-context-app.js` -### Consuming Multiple Contexts {#consuming-multiple-contexts} +### Использование нескольких контекстов {#consuming-multiple-contexts} -To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree. +Чтобы последующие рендеры (связанные с контекстом) были быстрыми, React делает каждого потребителя контекста отдельным компонентом в дереве. `embed:context/multiple-contexts.js` -If two or more context values are often used together, you might want to consider creating your own render prop component that provides both. +Если два или более значений контекста часто используются вместе, возможно, вам стоит рассмотреть создание отдельного компонента, который будет передавать оба значения дочерним компонентам с помощью паттерна «рендер-пропс». -## Caveats {#caveats} +## Предостережения {#caveats} -Because context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider's parent re-renders. For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for `value`: +Контекст использует сравнение по ссылкам, чтобы определить, когда запускать последующий рендер. Из-за этого существуют некоторые подводные камни, например, случайные повторные рендеры потребителей, при перерендере родителя Provider-компонента. В следующем примере будет происходить повторный рендер потребителя каждый повторный рендер Provider-компонента, потому что новый объект, передаваемый в `value`, будет создаваться каждый раз: `embed:context/reference-caveats-problem.js` - -To get around this, lift the value into the parent's state: +Один из вариантов решения этой проблемы — хранение этого объекта в состоянии родительского компонента: `embed:context/reference-caveats-solution.js` -## Legacy API {#legacy-api} +## Устаревший API {#legacy-api} -> Note -> -> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version. Read the [legacy context docs here](/docs/legacy-context.html). - +> Примечание +> +> В прошлом React имел только экспериментальный API контекстa. Старый API будет поддерживаться во всех 16.x релизах, но использующие его приложения должны перейти на новую версию. Устаревший API будет удалён в будущем крупном релизе React. Вы можете прочитать [документацию устаревшего контекста здесь](/docs/legacy-context.html). diff --git a/examples/context/motivation-problem.js b/examples/context/motivation-problem.js index d166f400a..ea4143afd 100644 --- a/examples/context/motivation-problem.js +++ b/examples/context/motivation-problem.js @@ -5,11 +5,12 @@ class App extends React.Component { } function Toolbar(props) { - // highlight-range{1-4,7} - // The Toolbar component must take an extra "theme" prop - // and pass it to the ThemedButton. This can become painful - // if every single button in the app needs to know the theme - // because it would have to be passed through all components. + // highlight-range{1-5,8} + // Компонент Toolbar должен передать проп "theme" ниже, + // фактически не используя его. Учитывая, что у вас в приложении + // могут быть десятки компонентов, использующих UI-тему, + // вам придётся передавать проп "theme" через все компоненты. + // И в какой-то момент это станет большой проблемой. return (
diff --git a/examples/context/motivation-solution.js b/examples/context/motivation-solution.js index 94c6030a9..018947eb8 100644 --- a/examples/context/motivation-solution.js +++ b/examples/context/motivation-solution.js @@ -1,15 +1,17 @@ -// highlight-range{1-4} -// Context lets us pass a value deep into the component tree -// without explicitly threading it through every component. -// Create a context for the current theme (with "light" as the default). +// highlight-range{1-5} +// Контекст позволяет передавать значение глубоко +// в дерево компонентов без явной передачи пропсов +// на каждом уровне. Создадим контекст для текущей +// UI-темы (со значением "light" по умолчанию). const ThemeContext = React.createContext('light'); class App extends React.Component { render() { - // highlight-range{1-3,5} - // Use a Provider to pass the current theme to the tree below. - // Any component can read it, no matter how deep it is. - // In this example, we're passing "dark" as the current value. + // highlight-range{1-4,6} + // Компонент Provider используется для передачи текущей + // UI-темы вниз по дереву. Любой компонент может использовать + // этот контекст и не важно, как глубоко он находится. + // В этом примере мы передаём "dark" в качестве значения контекста. return ( @@ -19,8 +21,8 @@ class App extends React.Component { } // highlight-range{1,2} -// A component in the middle doesn't have to -// pass the theme down explicitly anymore. +// Компонент, который находится в середине, +// теперь не должен явно передавать UI-тему вниз. function Toolbar(props) { return (
@@ -30,10 +32,11 @@ function Toolbar(props) { } class ThemedButton extends React.Component { - // highlight-range{1-3,6} - // Assign a contextType to read the current theme context. - // React will find the closest theme Provider above and use its value. - // In this example, the current theme is "dark". + // highlight-range{1-4,7} + // Определяем contextType, чтобы получить значение контекста. + // React найдёт (выше по дереву) ближайший Provider-компонент, + // предоставляющий этот контекст, и использует его значение. + // В этом примере значение UI-темы будет "dark". static contextType = ThemeContext; render() { return