Skip to content

Commit 7894371

Browse files
authored
Merge pull request #397 from 4johndoe/context
context page
2 parents 31ec1d3 + b6443a3 commit 7894371

File tree

3 files changed

+43
-43
lines changed

3 files changed

+43
-43
lines changed

content/docs/context.md

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
---
22
id: context
3-
title: Context
3+
title: Контекст
44
permalink: docs/context.html
55
---
66

7-
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
7+
Контекст забезпечує спосіб передавати дані через дерево компонентів без необхідності передавати пропси вручну на кожному рівні.
88

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 дані передаються зверху вниз (від батьківської до дочірньої компоненти) через пропси, але це може бути громіздким для певних типів реквізитів (наприклад, налаштування локалі, тема інтерфейсу користувача), які потрібні багатьом компонентам програми. Контекст надає спосіб обмінюватися значеннями, подібними до цих, між компонентами без необхідності явно передавати властивість через кожен рівень дерева.
1010

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)
1313
- [API](#api)
1414
- [React.createContext](#reactcreatecontext)
1515
- [Context.Provider](#contextprovider)
@@ -23,39 +23,39 @@ In a typical React application, data is passed top-down (parent to child) via pr
2323
- [Caveats](#caveats)
2424
- [Legacy API](#legacy-api)
2525

26-
## When to Use Context {#when-to-use-context}
26+
## Коли використовувати контекст {#when-to-use-context}
2727

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:
2929

3030
`embed:context/motivation-problem.js`
3131

32-
Using context, we can avoid passing props through intermediate elements:
32+
Використовуючи контекст, ми можемо уникнути проходження атрибутів через проміжні елементи:
3333

3434
`embed:context/motivation-solution.js`
3535

36-
## Before You Use Context {#before-you-use-context}
36+
## Перед використанням контексту {#before-you-use-context}
3737

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+
Контекст в основному використовується, коли деякі дані повинні бути доступні *багатьом* компонентам на різних рівнях вкладеності. Застосовуйте його економно, оскільки це ускладнює повторне використання компонентів.
3939

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) часто є простішим рішенням, ніж контекст.**
4141

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` могли прочитати його:
4343

4444
```js
4545
<Page user={user} avatarSize={avatarSize} />
46-
// ... which renders ...
46+
// ... який рендерить ...
4747
<PageLayout user={user} avatarSize={avatarSize} />
48-
// ... which renders ...
48+
// ... який рендерить ...
4949
<NavigationBar user={user} avatarSize={avatarSize} />
50-
// ... which renders ...
50+
// ... який рендерить ...
5151
<Link href={user.permalink}>
5252
<Avatar user={user} size={avatarSize} />
5353
</Link>
5454
```
5555

56-
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` потребує додаткових реквізитів зверху, ви також повинні додавати їх на всіх проміжних рівнях.
5757

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`:
5959

6060
```js
6161
function Page(props) {
@@ -68,21 +68,21 @@ function Page(props) {
6868
return <PageLayout userLink={userLink} />;
6969
}
7070

71-
// Now, we have:
71+
// Теперь ми маємо:
7272
<Page user={user} avatarSize={avatarSize} />
73-
// ... which renders ...
73+
// ... який рендерить ...
7474
<PageLayout userLink={...} />
75-
// ... which renders ...
75+
// ... який рендерить ...
7676
<NavigationBar userLink={...} />
77-
// ... which renders ...
77+
// ... який рендерить ...
7878
{props.userLink}
7979
```
8080

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`.
8282

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+
Ця *інверсія керування* може зробити ваш код чистішим у багатьох випадках, зменшивши кількість реквізитів, які потрібно пропустити через вашу програму, і надавши більше контролю кореневим компонентам. Однак це не завжди правильний вибір: переміщення більшої складності вище в дереві робить компоненти вищого рівня складнішими та змушує компоненти нижчого рівня бути більш гнучкими, ніж вам хочеться.
8484

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):
8686

8787
```js
8888
function Page(props) {
@@ -104,9 +104,9 @@ function Page(props) {
104104
}
105105
```
106106

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) якщо дочірня компонента потребує взаємодії з батьківською перед рендерингом.
108108

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+
Однак іноді ті самі дані повинні бути доступні багатьом компонентам у дереві та на різних рівнях вкладеності. Контекст дозволяє вам "транслювати" такі дані та зміни до них усім компонентам нижче. Поширені приклади, коли використання контексту може бути простішим, ніж альтернативи, включають керування поточною мовою, темою або кеш-пам’яттю даних.
110110

111111
## API {#api}
112112

@@ -116,9 +116,9 @@ However, sometimes the same data needs to be accessible by many components in th
116116
const MyContext = React.createContext(defaultValue);
117117
```
118118

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` над ним у дереві.
120120

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`.
122122

123123
### `Context.Provider` {#contextprovider}
124124

examples/context/motivation-problem.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ class App extends React.Component {
66

77
function Toolbar(props) {
88
// highlight-range{1-4,7}
9-
// The Toolbar component must take an extra "theme" prop
10-
// and pass it to the ThemedButton. This can become painful
11-
// if every single button in the app needs to know the theme
12-
// because it would have to be passed through all components.
9+
// Компонент Toolbar має приймати додатковий проп "theme"
10+
// та передавати його в ThemedButton. Це може стати проблемою
11+
// якщо кожна окрема кнопка в додатку повинна знати тему
12+
// оскільки його потрібно було б пропустити через усі компоненти.
1313
return (
1414
<div>
1515
<ThemedButton theme={props.theme} />

examples/context/motivation-solution.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
// highlight-range{1-4}
2-
// Context lets us pass a value deep into the component tree
3-
// without explicitly threading it through every component.
4-
// Create a context for the current theme (with "light" as the default).
2+
// Контекст дозволяє передати значення глибоко в дерево компонентів
3+
// без явного проходження через кожен компонент.
4+
// Створення контексту для поточної теми (з "light" за замовчуванням).
55
const ThemeContext = React.createContext('light');
66

77
class App extends React.Component {
88
render() {
99
// highlight-range{1-3,5}
10-
// Use a Provider to pass the current theme to the tree below.
11-
// Any component can read it, no matter how deep it is.
12-
// In this example, we're passing "dark" as the current value.
10+
// Використовуйте компонент Provider для передачі поточної теми в дерево нижче.
11+
// Будь-який компонент може прочитати його, незалежно від того, наскільки він глибокий.
12+
// У цьому прикладі ми передаємо "dark" як поточне значення.
1313
return (
1414
<ThemeContext.Provider value="dark">
1515
<Toolbar />
@@ -19,8 +19,8 @@ class App extends React.Component {
1919
}
2020

2121
// highlight-range{1,2}
22-
// A component in the middle doesn't have to
23-
// pass the theme down explicitly anymore.
22+
// Компонент посередині не обов’язково
23+
// передавати тему явно.
2424
function Toolbar() {
2525
return (
2626
<div>
@@ -31,9 +31,9 @@ function Toolbar() {
3131

3232
class ThemedButton extends React.Component {
3333
// highlight-range{1-3,6}
34-
// Assign a contextType to read the current theme context.
35-
// React will find the closest theme Provider above and use its value.
36-
// In this example, the current theme is "dark".
34+
// Призначте contextType для читання контексту поточної теми.
35+
// React знайде найближчий постачальник теми вище та використає його значення.
36+
// У цьому прикладі поточна тема "dark".
3737
static contextType = ThemeContext;
3838
render() {
3939
return <Button theme={this.context} />;

0 commit comments

Comments
 (0)