Skip to content

Commit 33aab23

Browse files
docs: translate createContext.md to Русский
1 parent 2958f53 commit 33aab23

1 file changed

Lines changed: 38 additions & 43 deletions

File tree

src/content/reference/react/createContext.md

Lines changed: 38 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
---
2-
title: createContext
3-
---
4-
51
<Intro>
62

7-
`createContext` lets you create a [context](/learn/passing-data-deeply-with-context) that components can provide or read.
3+
`createContext` позволяет создать [контекст](/learn/passing-data-deeply-with-context), который компоненты могут предоставлять или читать.
84

95
```js
106
const SomeContext = createContext(defaultValue)
@@ -16,38 +12,38 @@ const SomeContext = createContext(defaultValue)
1612

1713
---
1814

19-
## Reference {/*reference*/}
15+
## Справочник {/*reference*/}
2016

2117
### `createContext(defaultValue)` {/*createcontext*/}
2218

23-
Call `createContext` outside of any components to create a context.
19+
Вызовите `createContext` вне любого компонента, чтобы создать контекст.
2420

2521
```js
2622
import { createContext } from 'react';
2723

2824
const ThemeContext = createContext('light');
2925
```
3026

31-
[See more examples below.](#usage)
27+
[См. больше примеров ниже.](#usage)
3228

33-
#### Parameters {/*parameters*/}
29+
#### Параметры {/*parameters*/}
3430

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`. Значение по умолчанию предназначено как запасной вариант. Оно статично и никогда не меняется со временем.
3632

37-
#### Returns {/*returns*/}
33+
#### Возвращает {/*returns*/}
3834

39-
`createContext` returns a context object.
35+
`createContext` возвращает объект контекста.
4036

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) в компонентах ниже, чтобы прочитать его. Объект контекста имеет несколько свойств:
4238

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` — это альтернативный и редко используемый способ чтения значения контекста.
4541

4642
---
4743

4844
### `SomeContext.Provider` {/*provider*/}
4945

50-
Wrap your components into a context provider to specify the value of this context for all components inside:
46+
Оберните ваши компоненты в поставщика контекста, чтобы указать значение этого контекста для всех компонентов внутри:
5147

5248
```js
5349
function App() {
@@ -61,19 +57,19 @@ function App() {
6157
}
6258
```
6359

64-
#### Props {/*provider-props*/}
60+
#### Пропсы {/*provider-props*/}
6561

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` ближайшего соответствующего поставщика контекста над ним.
6763

6864
---
6965

7066
### `SomeContext.Consumer` {/*consumer*/}
7167

72-
Before `useContext` existed, there was an older way to read context:
68+
До появления `useContext` существовал старый способ чтения контекста:
7369

7470
```js
7571
function Button() {
76-
// 🟡 Legacy way (not recommended)
72+
// 🟡 Устаревший способ (не рекомендуется)
7773
return (
7874
<ThemeContext.Consumer>
7975
{theme => (
@@ -84,29 +80,29 @@ function Button() {
8480
}
8581
```
8682

87-
Although this older way still works, **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:**
83+
Хотя этот старый способ всё ещё работает, **новый код следует писать с использованием [`useContext()`](/reference/react/useContext):**
8884

8985
```js
9086
function Button() {
91-
//Recommended way
87+
//Рекомендуемый способ
9288
const theme = useContext(ThemeContext);
9389
return <button className={theme} />;
9490
}
9591
```
9692

97-
#### Props {/*consumer-props*/}
93+
#### Пропсы {/*consumer-props*/}
9894

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 всякий раз, когда контекст от родительских компонентов изменится.
10096

10197
---
10298

103-
## Usage {/*usage*/}
99+
## Использование {/*usage*/}
104100

105-
### Creating context {/*creating-context*/}
101+
### Создание контекста {/*creating-context*/}
106102

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), не передавая явно пропсы.
108104

109-
Call `createContext` outside any components to create one or more contexts.
105+
Вызовите `createContext` вне любого компонента, чтобы создать один или несколько контекстов.
110106

111107
```js [[1, 3, "ThemeContext"], [1, 4, "AuthContext"], [3, 3, "'light'"], [3, 4, "null"]]
112108
import { createContext } from 'react';
@@ -115,7 +111,7 @@ const ThemeContext = createContext('light');
115111
const AuthContext = createContext(null);
116112
```
117113

118-
`createContext` returns a <CodeStep step={1}>context object</CodeStep>. Components can read context by passing it to [`useContext()`](/reference/react/useContext):
114+
`createContext` возвращает <CodeStep step={1}>объект контекста</CodeStep>. Компоненты могут читать контекст, передавая его в [`useContext()`](/reference/react/useContext):
119115

120116
```js [[1, 2, "ThemeContext"], [1, 7, "AuthContext"]]
121117
function Button() {
@@ -129,9 +125,9 @@ function Profile() {
129125
}
130126
```
131127

132-
By default, the values they receive will be the <CodeStep step={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+
По умолчанию значения, которые они получают, будут <CodeStep step={3}>значениями по умолчанию</CodeStep>, которые вы указали при создании контекстов. Однако само по себе это не очень полезно, так как значения по умолчанию никогда не меняются.
133129

134-
Context is useful because you can **provide other, dynamic values from your components:**
130+
Контекст полезен, потому что вы можете **предоставлять другие, динамические значения из ваших компонентов:**
135131

136132
```js {8-9,11-12}
137133
function App() {
@@ -150,15 +146,15 @@ function App() {
150146
}
151147
```
152148

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 также повторно отрисует компоненты, читающие контекст.
154150

155-
[Read more about reading and providing context and see examples.](/reference/react/useContext)
151+
[Узнайте больше о чтении и предоставлении контекста и посмотрите примеры.](/reference/react/useContext)
156152

157153
---
158154

159-
### Importing and exporting context from a file {/*importing-and-exporting-context-from-a-file*/}
155+
### Импорт и экспорт контекста из файла {/*importing-and-exporting-context-from-a-file*/}
160156

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), чтобы сделать контекст доступным для других файлов:
162158

163159
```js {4-5}
164160
// Contexts.js
@@ -168,7 +164,7 @@ export const ThemeContext = createContext('light');
168164
export const AuthContext = createContext(null);
169165
```
170166

171-
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) для чтения или предоставления этого контекста:
172168

173169
```js {2}
174170
// Button.js
@@ -196,22 +192,21 @@ function App() {
196192
}
197193
```
198194

199-
This works similar to [importing and exporting components.](/learn/importing-and-exporting-components)
195+
Это работает аналогично [импорту и экспорту компонентов.](/learn/importing-and-exporting-components)
200196

201197
---
202198

203-
## Troubleshooting {/*troubleshooting*/}
199+
## Устранение неполадок {/*troubleshooting*/}
204200

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*/}
206202

207203

208-
Code like this specifies the *default* context value:
204+
Код вроде этого указывает *значение контекста по умолчанию*:
209205

210206
```js
211207
const ThemeContext = createContext('light');
212208
```
213209

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 использует это значение только в качестве запасного варианта, если не может найти соответствующего поставщика выше.
217211

212+
Чтобы контекст менялся со временем, [добавьте состояние и оберните компоненты в поставщика контекста.](/reference/react/useContext#updating-data-passed-via-context)

0 commit comments

Comments
 (0)