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
Copy file name to clipboardExpand all lines: content/docs/context.md
+28-28Lines changed: 28 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,15 +1,15 @@
1
1
---
2
2
id: context
3
-
title: Context
3
+
title: Контекст
4
4
permalink: docs/context.html
5
5
---
6
6
7
-
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
7
+
Контекст забезпечує спосіб передавати дані через дерево компонентів без необхідності передавати пропси вручну на кожному рівні.
8
8
9
-
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.
9
+
У типовому додатку React дані передаються зверху вниз (від батьківської до дочірньої компоненти) через пропси, але це може бути громіздким для певних типів реквізитів (наприклад, налаштування локалі, тема інтерфейсу користувача), які потрібні багатьом компонентам програми. Контекст надає спосіб обмінюватися значеннями, подібними до цих, між компонентами без необхідності явно передавати властивість через кожен рівень дерева.
10
10
11
-
-[When to Use Context](#when-to-use-context)
12
-
-[Before You Use Context](#before-you-use-context)
11
+
-[Коли використовувати контекст](#when-to-use-context)
12
+
-[Перед використанням контексту](#before-you-use-context)
13
13
-[API](#api)
14
14
-[React.createContext](#reactcreatecontext)
15
15
-[Context.Provider](#contextprovider)
@@ -23,39 +23,39 @@ In a typical React application, data is passed top-down (parent to child) via pr
23
23
-[Caveats](#caveats)
24
24
-[Legacy API](#legacy-api)
25
25
26
-
## When to Use Context {#when-to-use-context}
26
+
## Коли використовувати контекст {#when-to-use-context}
27
27
28
-
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:
28
+
Контекст призначений для обміну даними, які можна вважати «глобальними» для дерева компонентів React, таких як поточний автентифікований користувач, тема чи бажана мова. Наприклад, у наведеному нижче коді ми вручну прокидаємо проп `theme`, щоб стилізувати компонент Button:
29
29
30
30
`embed:context/motivation-problem.js`
31
31
32
-
Using context, we can avoid passing props through intermediate elements:
32
+
Використовуючи контекст, ми можемо уникнути проходження атрибутів через проміжні елементи:
33
33
34
34
`embed:context/motivation-solution.js`
35
35
36
-
## Before You Use Context {#before-you-use-context}
36
+
## Перед використанням контексту {#before-you-use-context}
37
37
38
-
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.
38
+
Контекст в основному використовується, коли деякі дані повинні бути доступні *багатьом* компонентам на різних рівнях вкладеності. Застосовуйте його економно, оскільки це ускладнює повторне використання компонентів.
39
39
40
-
**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.**
40
+
**Якщо ви тільки хочете уникнути проходження деяких реквізитів через багато рівнів, [композиція компонентів](/docs/composition-vs-inheritance.html)часто є простішим рішенням, ніж контекст.**
41
41
42
-
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:
42
+
Наприклад, розглянемо компонент`Page`, який передає властивість `user`і`avatarSize`на кілька рівнів нижче, щоб глибоко вкладені компоненти`Link`і`Avatar`могли прочитати його:
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.
56
+
Може здатися зайвим передавати властивості `user`і`avatarSize`через багато рівнів, якщо зрештою вони дійсно потрібні лише компоненту`Avatar`. Також дратує те, що щоразу, коли компонент `Avatar`потребує додаткових реквізитів зверху, ви також повинні додавати їх на всіх проміжних рівнях.
57
57
58
-
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`or`avatarSize` props:
58
+
Один із способів вирішити цю проблему**без контексту**— це [передавати сам компонент`Avatar`](/docs/composition-vs-inheritance.html#containment)щоб проміжним компонентам не потрібно було знати про властивості `user`або`avatarSize`:
59
59
60
60
```js
61
61
functionPage(props) {
@@ -68,21 +68,21 @@ function Page(props) {
68
68
return<PageLayout userLink={userLink} />;
69
69
}
70
70
71
-
//Now, we have:
71
+
//Теперь ми маємо:
72
72
<Page user={user} avatarSize={avatarSize} />
73
-
// ... which renders ...
73
+
// ... який рендерить ...
74
74
<PageLayout userLink={...} />
75
-
// ... which renders ...
75
+
// ... який рендерить ...
76
76
<NavigationBar userLink={...} />
77
-
// ... which renders ...
77
+
// ... який рендерить ...
78
78
{props.userLink}
79
79
```
80
80
81
-
With this change, only the top-most Page component needs to know about the `Link` and `Avatar` components' use of `user` and `avatarSize`.
81
+
Завдяки цій зміні лише верхній компонент Page має знати про використання `user` і `avatarSize` компонентами `Link` і `Avatar`.
82
82
83
-
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.
83
+
Ця *інверсія керування* може зробити ваш код чистішим у багатьох випадках, зменшивши кількість реквізитів, які потрібно пропустити через вашу програму, і надавши більше контролю кореневим компонентам. Однак це не завжди правильний вибір: переміщення більшої складності вище в дереві робить компоненти вищого рівня складнішими та змушує компоненти нижчого рівня бути більш гнучкими, ніж вам хочеться.
84
84
85
-
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):
85
+
Ви не обмежені одним дочірнім компонентом. Ви можете передати кілька дочірніх компонентів або навіть мати кілька окремих "слотів" для дочірніх компонентів, [як описано тут](/docs/composition-vs-inheritance.html#containment):
86
86
87
87
```js
88
88
functionPage(props) {
@@ -104,9 +104,9 @@ function Page(props) {
104
104
}
105
105
```
106
106
107
-
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.
107
+
Ціого паттерну достатньо для багатьох випадків, коли потрібно відділити дочірній компонент від найближчих батьків. Ви можете піти ще далі за допомогою [рендер-пропси](/docs/render-props.html)якщо дочірня компонента потребує взаємодії з батьківською перед рендерингом.
108
108
109
-
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.
109
+
Однак іноді ті самі дані повинні бути доступні багатьом компонентам у дереві та на різних рівнях вкладеності. Контекст дозволяє вам "транслювати" такі дані та зміни до них усім компонентам нижче. Поширені приклади, коли використання контексту може бути простішим, ніж альтернативи, включають керування поточною мовою, темою або кеш-пам’яттю даних.
110
110
111
111
## API {#api}
112
112
@@ -116,9 +116,9 @@ However, sometimes the same data needs to be accessible by many components in th
116
116
constMyContext=React.createContext(defaultValue);
117
117
```
118
118
119
-
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.
119
+
Створює об’єкт Context. Коли React відтворює компонент, який підписується на цей об’єкт Context, він читатиме поточне значення контексту з найближчого відповідного `Provider`над ним у дереві.
120
120
121
-
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`.
121
+
Аргумент`defaultValue`використовується **тільки**, коли компонент не має відповідного провайдера над ним у дереві. Це може бути корисним для тестування компонентів ізольовано без їх упаковки. Примітка: передача`undefined`як значення провайдера не призводить до використання споживаючими компонентами`defaultValue`.
0 commit comments