You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Call`createContext`outside of any components to create a context.
19
+
Вызовите`createContext`вне любого компонента, чтобы создать контекст.
24
20
25
21
```js
26
22
import { createContext } from'react';
27
23
28
24
constThemeContext=createContext('light');
29
25
```
30
26
31
-
[See more examples below.](#usage)
27
+
[См. больше примеров ниже.](#usage)
32
28
33
-
#### Parameters {/*parameters*/}
29
+
#### Параметры {/*parameters*/}
34
30
35
-
*`defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify`null`. The default value is meant as a "last resort" fallback. It is static and never changes over time.
31
+
*`defaultValue`: Значение, которое вы хотите присвоить контексту, когда в дереве над компонентом, читающим контекст, нет соответствующего поставщика контекста. Если у вас нет значимого значения по умолчанию, укажите`null`. Значение по умолчанию предназначено как запасной вариант. Оно статично и никогда не меняется со временем.
36
32
37
-
#### Returns {/*returns*/}
33
+
#### Возвращает {/*returns*/}
38
34
39
-
`createContext`returns a context object.
35
+
`createContext`возвращает объект контекста.
40
36
41
-
**The context object itself does not hold any information.**It represents _which_ context other components read or provide. Typically, you will use[`SomeContext.Provider`](#provider)in components above to specify the context value, and call[`useContext(SomeContext)`](/reference/react/useContext)in components below to read it. The context object has a few properties:
37
+
**Сам объект контекста не содержит никакой информации.**Он представляет собой _идентификатор_, который другие компоненты читают или предоставляют. Обычно вы будете использовать[`SomeContext.Provider`](#provider)в компонентах выше, чтобы указать значение контекста, и вызывать[`useContext(SomeContext)`](/reference/react/useContext)в компонентах ниже, чтобы прочитать его. Объект контекста имеет несколько свойств:
42
38
43
-
*`SomeContext.Provider`lets you provide the context value to components.
44
-
*`SomeContext.Consumer`is an alternative and rarely used way to read the context value.
39
+
*`SomeContext.Provider`позволяет предоставлять значение контекста компонентам.
40
+
*`SomeContext.Consumer`— это альтернативный и редко используемый способ чтения значения контекста.
45
41
46
42
---
47
43
48
44
### `SomeContext.Provider` {/*provider*/}
49
45
50
-
Wrap your components into a context provider to specify the value of this context for all components inside:
46
+
Оберните ваши компоненты в поставщика контекста, чтобы указать значение этого контекста для всех компонентов внутри:
51
47
52
48
```js
53
49
functionApp() {
@@ -61,19 +57,19 @@ function App() {
61
57
}
62
58
```
63
59
64
-
#### Props {/*provider-props*/}
60
+
#### Пропсы {/*provider-props*/}
65
61
66
-
*`value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext)inside of the provider receives the `value`of the innermost corresponding context provider above it.
62
+
*`value`: Значение, которое вы хотите передать всем компонентам, читающим этот контекст внутри этого поставщика, независимо от их глубины. Значение контекста может быть любого типа. Компонент, вызывающий [`useContext(SomeContext)`](/reference/react/useContext)внутри поставщика, получает `value`ближайшего соответствующего поставщика контекста над ним.
67
63
68
64
---
69
65
70
66
### `SomeContext.Consumer` {/*consumer*/}
71
67
72
-
Before `useContext`existed, there was an older way to read context:
68
+
До появления `useContext`существовал старый способ чтения контекста:
73
69
74
70
```js
75
71
functionButton() {
76
-
// 🟡 Legacy way (not recommended)
72
+
// 🟡 Устаревший способ (не рекомендуется)
77
73
return (
78
74
<ThemeContext.Consumer>
79
75
{theme=> (
@@ -84,29 +80,29 @@ function Button() {
84
80
}
85
81
```
86
82
87
-
Although this older way still works, **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:**
83
+
Хотя этот старый способ всё ещё работает, **новый код следует писать с использованием [`useContext()`](/reference/react/useContext):**
88
84
89
85
```js
90
86
functionButton() {
91
-
// ✅ Recommended way
87
+
// ✅ Рекомендуемый способ
92
88
consttheme=useContext(ThemeContext);
93
89
return<button className={theme} />;
94
90
}
95
91
```
96
92
97
-
#### Props {/*consumer-props*/}
93
+
#### Пропсы {/*consumer-props*/}
98
94
99
-
*`children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/reference/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes.
95
+
*`children`: Функция. React вызовет функцию, которую вы передали, с текущим значением контекста, определённым тем же алгоритмом, что и [`useContext()`](/reference/react/useContext), и отрисует результат, который вы вернёте из этой функции. React также будет повторно вызывать эту функцию и обновлять UI всякий раз, когда контекст от родительских компонентов изменится.
100
96
101
97
---
102
98
103
-
## Usage {/*usage*/}
99
+
## Использование {/*usage*/}
104
100
105
-
### Creating context {/*creating-context*/}
101
+
### Создание контекста {/*creating-context*/}
106
102
107
-
Context lets components [pass information deep down](/learn/passing-data-deeply-with-context) without explicitly passing props.
103
+
Контекст позволяет компонентам [передавать информацию глубоко вниз](/learn/passing-data-deeply-with-context), не передавая явно пропсы.
108
104
109
-
Call`createContext`outside any components to create one or more contexts.
105
+
Вызовите`createContext`вне любого компонента, чтобы создать один или несколько контекстов.
`createContext`returns a <CodeStepstep={1}>context object</CodeStep>. Components can read context by passing it to[`useContext()`](/reference/react/useContext):
114
+
`createContext`возвращает <CodeStepstep={1}>объект контекста</CodeStep>. Компоненты могут читать контекст, передавая его в[`useContext()`](/reference/react/useContext):
By default, the values they receive will be the <CodeStepstep={3}>default values</CodeStep> you have specified when creating the contexts. However, by itself this isn't useful because the default values never change.
128
+
По умолчанию значения, которые они получают, будут <CodeStepstep={3}>значениями по умолчанию</CodeStep>, которые вы указали при создании контекстов. Однако само по себе это не очень полезно, так как значения по умолчанию никогда не меняются.
133
129
134
-
Context is useful because you can**provide other, dynamic values from your components:**
130
+
Контекст полезен, потому что вы можете**предоставлять другие, динамические значения из ваших компонентов:**
135
131
136
132
```js {8-9,11-12}
137
133
functionApp() {
@@ -150,15 +146,15 @@ function App() {
150
146
}
151
147
```
152
148
153
-
Now the`Page`component and any components inside it, no matter how deep, will "see" the passed context values. If the passed context values change, React will re-render the components reading the context as well.
149
+
Теперь компонент`Page`и любые компоненты внутри него, независимо от их глубины, будут «видеть» переданные значения контекста. Если переданные значения контекста изменятся, React также повторно отрисует компоненты, читающие контекст.
154
150
155
-
[Read more about reading and providing context and see examples.](/reference/react/useContext)
151
+
[Узнайте больше о чтении и предоставлении контекста и посмотрите примеры.](/reference/react/useContext)
156
152
157
153
---
158
154
159
-
### Importing and exporting context from a file {/*importing-and-exporting-context-from-a-file*/}
155
+
### Импорт и экспорт контекста из файла {/*importing-and-exporting-context-from-a-file*/}
160
156
161
-
Often, components in different files will need access to the same context. This is why it's common to declare contexts in a separate file. Then you can use the [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make context available for other files:
157
+
Часто компонентам в разных файлах потребуется доступ к одному и тому же контексту. Поэтому принято объявлять контексты в отдельном файле. Затем вы можете использовать [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export), чтобы сделать контекст доступным для других файлов:
Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import)statement to read or provide this context:
167
+
Компоненты, объявленные в других файлах, затем могут использовать [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import)для чтения или предоставления этого контекста:
172
168
173
169
```js {2}
174
170
// Button.js
@@ -196,22 +192,21 @@ function App() {
196
192
}
197
193
```
198
194
199
-
This works similar to [importing and exporting components.](/learn/importing-and-exporting-components)
195
+
Это работает аналогично [импорту и экспорту компонентов.](/learn/importing-and-exporting-components)
200
196
201
197
---
202
198
203
-
## Troubleshooting {/*troubleshooting*/}
199
+
## Устранение неполадок {/*troubleshooting*/}
204
200
205
-
### I can't find a way to change the context value {/*i-cant-find-a-way-to-change-the-context-value*/}
201
+
### Я не могу найти способ изменить значение контекста {/*i-cant-find-a-way-to-change-the-context-value*/}
206
202
207
203
208
-
Code like this specifies the *default* context value:
204
+
Код вроде этого указывает *значение контекста по умолчанию*:
209
205
210
206
```js
211
207
constThemeContext=createContext('light');
212
208
```
213
209
214
-
This value never changes. React only uses this value as a fallback if it can't find a matching provider above.
215
-
216
-
To make context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context)
210
+
Это значение никогда не меняется. React использует это значение только в качестве запасного варианта, если не может найти соответствующего поставщика выше.
217
211
212
+
Чтобы контекст менялся со временем, [добавьте состояние и оберните компоненты в поставщика контекста.](/reference/react/useContext#updating-data-passed-via-context)
0 commit comments