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: src/content/learn/sharing-state-between-components.md
+51-51
Original file line number
Diff line number
Diff line change
@@ -283,48 +283,48 @@ h3, p { margin: 5px 0px; }
283
283
284
284
<DeepDive>
285
285
286
-
#### Controlled and uncontrolled components {/*controlled-and-uncontrolled-components*/}
286
+
#### Контрольовані та неконтрольовані компоненти {/*controlled-and-uncontrolled-components*/}
287
287
288
-
It is common to call a component with some local state "uncontrolled". For example, the original `Panel`component with an `isActive`state variable is uncontrolled because its parent cannot influence whether the panel is active or not.
288
+
Прийнято називати деякий компонент із локальним станом "неконтрольованим". Для прикладу, вихідний `Panel`компонент із `isActive`змінною стану є неконтрольований, оскільки його батько не може впливати на те, чи буде панель активною чи ні.
289
289
290
-
In contrast, you might say a component is "controlled" when the important information in it is driven by props rather than its own local state. This lets the parent component fully specify its behavior. The final `Panel`component with the `isActive`prop is controlled by the `Accordion` component.
290
+
На противагу, ви можете сказати що компонент є "контрольований" коли важлива інформація в ньому керується за допомогою пропсів а не його власним локальним станом. Це дозволяє батьківському компоненту повністю визанчити його поведінку. Останній `Panel`компонент із `isActive`проп є контрольований компонентом `Accordion`.
291
291
292
-
Uncontrolled components are easier to use within their parents because they require less configuration. But they're less flexible when you want to coordinate them together. Controlled components are maximally flexible, but they require the parent components to fully configure them with props.
292
+
Неконтрольовані компоненти легше використовувати із їхніми батьківськими, оскільки вони вимагають менше налаштувань. Але вони менш гнучкі, коли ви хочете скоординувати їх разом. Контрольовані компоненти є максимально гнучкими але вони вимагають від батьківських компонент повністю налаштувати їх за допомогою пропсів.
293
293
294
-
In practice, "controlled" and "uncontrolled" aren't strict technical terms--each component usually has some mix of both local state and props. However, this is a useful way to talk about how components are designed and what capabilities they offer.
294
+
На практиці, "контрольований" та "неконтрольований" не є строгими технічними термінами--кожен компонент, зазвичай має суміш обох, із локальним станом та пропсами. Однак, це корисний спосіб, щоб поговорити як компоненти спроектовані, та які можливості вони пропонують.
295
295
296
-
When writing a component, consider which information in it should be controlled (via props), and which information should be uncontrolled (via state). But you can always change your mind and refactor later.
296
+
Коли пишите компонент, подумайте, яка інформація в ньому має бути контрольованою (за допомогою пропсів), а яка інформація має бути неконтрольована (за допомогою стану). Але завжди можете передумати і покращити це пізніше.
297
297
298
298
</DeepDive>
299
299
300
-
## A single source of truth for each state {/*a-single-source-of-truth-for-each-state*/}
300
+
## Єдине джерело правди для кожного стану {/*a-single-source-of-truth-for-each-state*/}
301
301
302
-
In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React state, and passing it down by props!
302
+
В React застосунку, багато компонент матимуть їхній власний стан. Деякий стан може "жити" близько до листкових компонент (компоненти, що знаходяться внизу дерева), для прикладу, поля вводу. Інші стани можуть "жити" ближче до вершини застосунку. Для прикладу, навіть клієнтські бібліотеки маршрутизації зазвичай реалізовані за допомогою зберігання поточного маршруту в React стані та передають його вниз за допомогою пропсів!
303
303
304
-
**For each unique piece of state, you will choose the component that "owns" it.** This principle is also known as having a ["single source of truth".](https://en.wikipedia.org/wiki/Single_source_of_truth) It doesn't mean that all state lives in one place--but that for _each_ piece of state, there is a _specific_ component that holds that piece of information. Instead of duplicating shared state between components, *lift it up* to their common shared parent, and *pass it down* to the children that need it.
304
+
**Для кожної унікальної частинки стану, ви вибирете компонент що "належить" йому.** Цей принцип також відомий як ["єдине джерело правди"](https://en.wikipedia.org/wiki/Single_source_of_truth) Це не означає, що весь стан знаходиться в одному місці--це означає, що для _кожної_ частини стану існує _певний_ компонент, який містить ту частину інформації. Замість дублювання спільного стану між компонентами, *підніміть його вгору* до їхнього спільного батька та *передайте його вниз* до дочірніх компонент, де він потрібний.
305
305
306
-
Your app will change as you work on it. It is common that you will move state down or back up while you're still figuring out where each piece of the state "lives". This is all part of the process!
306
+
Ваш застосунок буде змінюватись в міру того, як ви працюєте над ним. Часто буває так. що ви переміщуєте стан вниз або назад вгору, протягом того, як стараєтесь з'ясувати де кожен шматок стану "живе". Це все частина процесу!
307
307
308
-
To see what this feels like in practice with a few more components, read [Thinking in React.](/learn/thinking-in-react)
308
+
Щоб побачити, як це виглядає на практиці з кількома іншими компонентами, читайте [Мислення в React.](/learn/thinking-in-react)
309
309
310
310
<Recap>
311
311
312
-
* When you want to coordinate two components, move their state to their common parent.
313
-
* Then pass the information down through props from their common parent.
314
-
* Finally, pass the event handlers down so that the children can change the parent's state.
315
-
* It's useful to consider components as "controlled" (driven by props) or "uncontrolled" (driven by state).
312
+
* Коли ви хочете скоординувати два компоненти, перенесіть їхній стан до їхнього спільного батька.
313
+
* Потім передайте інформацію вниз через пропси від їхнього спільного батька.
314
+
* Нарешті, передайте обробник подій вниз, щоб діти могли змінювати батьківський стан.
315
+
* Корисно розглядати компонент як "контрольований" (керований пропсами) або "неконтрольований" (керований станом).
316
316
317
317
</Recap>
318
318
319
319
<Challenges>
320
320
321
-
#### Synced inputs {/*synced-inputs*/}
321
+
#### Синхронізовані поля вводу {/*synced-inputs*/}
322
322
323
-
These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa.
323
+
Ці два поля вводу є незалежні. Зробіть так, щоб вони були синхронізовані: редагування одного поля вводу має оновлювати інше поле вводу із тим самим текстом, і навпаки.
324
324
325
325
<Hint>
326
326
327
-
You'll need to lift their state up into the parent component.
327
+
Вам потрібно підняти їхній стан вгору до батьківського компонентам.
328
328
329
329
</Hint>
330
330
@@ -336,8 +336,8 @@ import { useState } from 'react';
336
336
exportdefaultfunctionSyncedInputs() {
337
337
return (
338
338
<>
339
-
<Input label="First input"/>
340
-
<Input label="Second input"/>
339
+
<Input label="Перше поле вводу"/>
340
+
<Input label="Друге поле вводу"/>
341
341
</>
342
342
);
343
343
}
@@ -371,7 +371,7 @@ label { display: block; }
371
371
372
372
<Solution>
373
373
374
-
Move the `text`state variable into the parent component along with the `handleChange`handler. Then pass them down as props to both of the `Input`components. This will keep them in sync.
374
+
Пересіть змінну стану `text`в батьківський компонент разом із `handleChange`обробником. Потім передайте їх вниз як пропси до обох `Input`компонент. Це забезпечить їхню синхронізацію.
375
375
376
376
<Sandpack>
377
377
@@ -388,12 +388,12 @@ export default function SyncedInputs() {
388
388
return (
389
389
<>
390
390
<Input
391
-
label="First input"
391
+
label="Перше поле вводу"
392
392
value={text}
393
393
onChange={handleChange}
394
394
/>
395
395
<Input
396
-
label="Second input"
396
+
label="Друге поле вводу"
397
397
value={text}
398
398
onChange={handleChange}
399
399
/>
@@ -424,17 +424,17 @@ label { display: block; }
424
424
425
425
</Solution>
426
426
427
-
#### Filtering a list {/*filtering-a-list*/}
427
+
#### Фільтрування списку {/*filtering-a-list*/}
428
428
429
-
In this example, the `SearchBar`has its own `query`state that controls the text input. Its parent`FilterableList`component displays a `List`of items, but it doesn't take the search query into account.
429
+
В цьому прикладі, `SearchBar`має власний `query`стан що контролює текстове поле вводу. Його батьківський`FilterableList`компонент відображає `List`елементів але це не враховує пошуковий запит.
430
430
431
-
Use the `filterItems(foods, query)`function to filter the list according to the search query. To test your changes, verify that typing "s" into the input filters down the list to "Sushi", "Shish kebab", and "Dim sum".
431
+
Використайте `filterItems(foods, query)`функцію щоб фільтрувати список відповідно до пошукового запиту. Щоб перевірити ваші зміни, переконайтеся, що введення "с" в поле введення відфільтрує список до "Суші", та "Дім сум".
432
432
433
-
Note that `filterItems`is already implemented and imported so you don't need to write it yourself!
433
+
Зверніть увагу, що `filterItems`вже реалізовано та імпортовано, отже вам не потрібно писати його самостійно!
434
434
435
435
<Hint>
436
436
437
-
You will want to remove the `query`state and the `handleChange`handler from the `SearchBar`, and move them to the `FilterableList`. Then pass them down to`SearchBar`as`query`and`onChange`props.
437
+
Вам потрібно видалити стан `query`та `handleChange`обробник з `SearchBar`, та перенести їх до `FilterableList`. Потім передати їх вниз до`SearchBar`як`query`та`onChange`пропси.
438
438
439
439
</Hint>
440
440
@@ -463,7 +463,7 @@ function SearchBar() {
463
463
464
464
return (
465
465
<label>
466
-
Search:{''}
466
+
Пошук:{''}
467
467
<input
468
468
value={query}
469
469
onChange={handleChange}
@@ -500,32 +500,32 @@ export function filterItems(items, query) {
500
500
501
501
exportconstfoods= [{
502
502
id:0,
503
-
name:'Sushi',
504
-
description:'Sushi is a traditional Japanese dish of prepared vinegared rice'
503
+
name:'Суші',
504
+
description:'Суші - традиційна японська страва з готового рису, заправленого оцтом'
505
505
}, {
506
506
id:1,
507
-
name:'Dal',
508
-
description:'The most common way of preparing dal is in the form of a soup to which onions, tomatoes and various spices may be added'
507
+
name:'Дал',
508
+
description:'Найпоширеніший спосіб приготування дала - у вигляді супу, до якого можуть додавати цибулю, помідори та різні спеції'
509
509
}, {
510
510
id:2,
511
-
name:'Pierogi',
512
-
description:'Pierogi are filled dumplings made by wrapping unleavened dough around a savoury or sweet filling and cooking in boiling water'
511
+
name:'Пиріжки',
512
+
description:'Пиріжки - це вареники з начинкою, які готуються шляхом обгортання прісного тіста навколо солоної або солодкої начинки і варіння в киплячій воді'
513
513
}, {
514
514
id:3,
515
-
name:'Shish kebab',
516
-
description:'Shish kebab is a popular meal of skewered and grilled cubes of meat.'
515
+
name:'Шиш-кебаб',
516
+
description:'Шиш-кебаб - популярна страва з кубиків м\'яса, нанизаних на шампур і приготованих на грилі.'
517
517
}, {
518
518
id:4,
519
-
name:'Dim sum',
520
-
description:'Dim sum is a large range of small dishes that Cantonese people traditionally enjoy in restaurants for breakfast and lunch'
519
+
name:'Дім сум',
520
+
description:'Дім сум - це великий асортимент невеликих страв, якими кантонці традиційно насолоджуються в ресторанах на сніданок та обід.'
521
521
}];
522
522
```
523
523
524
524
</Sandpack>
525
525
526
526
<Solution>
527
527
528
-
Lift the`query` state up into the `FilterableList`component. Call`filterItems(foods, query)`to get the filtered list and pass it down to the `List`. Now changing the query input is reflected in the list:
528
+
Підніміть стан`query`вгору в `FilterableList`компонент. Викличте`filterItems(foods, query)`щоб отримати відфільтрований список і передати його вниз до `List`. Тепер зміна пошукових даних вводу відображається в списку:
529
529
530
530
<Sandpack>
531
531
@@ -556,7 +556,7 @@ export default function FilterableList() {
556
556
functionSearchBar({ query, onChange }) {
557
557
return (
558
558
<label>
559
-
Search:{''}
559
+
Пошук:{''}
560
560
<input
561
561
value={query}
562
562
onChange={onChange}
@@ -593,24 +593,24 @@ export function filterItems(items, query) {
593
593
594
594
exportconstfoods= [{
595
595
id:0,
596
-
name:'Sushi',
597
-
description:'Sushi is a traditional Japanese dish of prepared vinegared rice'
596
+
name:'Суші',
597
+
description:'Суші - традиційна японська страва з готового рису, заправленого оцтом'
598
598
}, {
599
599
id:1,
600
-
name:'Dal',
601
-
description:'The most common way of preparing dal is in the form of a soup to which onions, tomatoes and various spices may be added'
600
+
name:'Дал',
601
+
description:'Найпоширеніший спосіб приготування дала - у вигляді супу, до якого можуть додавати цибулю, помідори та різні спеції'
602
602
}, {
603
603
id:2,
604
-
name:'Pierogi',
605
-
description:'Pierogi are filled dumplings made by wrapping unleavened dough around a savoury or sweet filling and cooking in boiling water'
604
+
name:'Пиріжки',
605
+
description:'Пиріжки - це вареники з начинкою, які готуються шляхом обгортання прісного тіста навколо солоної або солодкої начинки і варіння в киплячій воді'
606
606
}, {
607
607
id:3,
608
-
name:'Shish kebab',
609
-
description:'Shish kebab is a popular meal of skewered and grilled cubes of meat.'
608
+
name:'Шиш-кебаб',
609
+
description:'Шиш-кебаб - популярна страва з кубиків м\'яса, нанизаних на шампур і приготованих на грилі.'
610
610
}, {
611
611
id:4,
612
-
name:'Dim sum',
613
-
description:'Dim sum is a large range of small dishes that Cantonese people traditionally enjoy in restaurants for breakfast and lunch'
612
+
name:'Дім сум',
613
+
description:'Дім сум - це великий асортимент невеликих страв, якими кантонці традиційно насолоджуються в ресторанах на сніданок та обід.'
0 commit comments