Skip to content

Commit d65deb2

Browse files
pasichnykoleksii-polovyi
authored andcommitted
Translation of Forwarding refs and some fixes (#156)
* translated forwarding-refs translation without comments * updated forwarding-ref translation translated code comments * fixed typo in optimizing-performance * fixed forwarding-ref translation updated translation * fixed typo in reference-react-component * translation fixes in forwarding-ref * Apply suggestions from code review Co-Authored-By: Volodymyr Klymenko <[email protected]> * Apply suggestions from code review Co-Authored-By: Volodymyr Klymenko <[email protected]> * removed line * Apply suggestions from code review Co-Authored-By: Oleksii Polovyi <[email protected]>
1 parent 73b32af commit d65deb2

File tree

8 files changed

+47
-47
lines changed

8 files changed

+47
-47
lines changed

content/docs/forwarding-refs.md

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,76 @@
11
---
22
id: forwarding-refs
3-
title: Forwarding Refs
3+
title: Перенаправлення рефів
44
permalink: docs/forwarding-refs.html
55
---
66

7-
Ref forwarding is a technique for automatically passing a [ref](/docs/refs-and-the-dom.html) through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below.
7+
Перенаправлення рефів — це техніка для автоматичної передачі [рефа](/docs/refs-and-the-dom.html) від компонента до одного із його дітей. Для більшості компонентів, зазвичай, вона не є необхідною. Тим не менше, може бути корисною в деяких випадках, особливо якщо ви пишете бібліотеку. Давайте розглянемо найбільш поширені сценарії.
88

9-
## Forwarding refs to DOM components {#forwarding-refs-to-dom-components}
9+
## Перенаправлення рефів у DOM-компоненти {#forwarding-refs-to-dom-components}
1010

11-
Consider a `FancyButton` component that renders the native `button` DOM element:
11+
Розглянемо компонент `FancyButton`, який рендерить нативний DOM-елемент `button`:
1212
`embed:forwarding-refs/fancy-button-simple.js`
1313

14-
React components hide their implementation details, including their rendered output. Other components using `FancyButton` **usually will not need to** [obtain a ref](/docs/refs-and-the-dom.html) to the inner `button` DOM element. This is good because it prevents components from relying on each other's DOM structure too much.
14+
React-компоненти приховують деталі своєї реалізації та результат рендеренгу. Також іншим компонентам, які використовують `FancyButton`, **зазвичай не потрібен** [доступ до рефа](/docs/refs-and-the-dom.html) його внутрішньому DOM-елементу `button`. І це добре тим, що це запобігає надмірній залежності компонентів від структури DOM-у один одного.
1515

16-
Although such encapsulation is desirable for application-level components like `FeedStory` or `Comment`, it can be inconvenient for highly reusable "leaf" components like `FancyButton` or `MyTextInput`. These components tend to be used throughout the application in a similar manner as a regular DOM `button` and `input`, and accessing their DOM nodes may be unavoidable for managing focus, selection, or animations.
16+
Хоча, така інкапсуляція є бажаною для компонентів, які описують певну закінчену частину додатка, наприклад, `FeedStory` або `Comment`, це може бути незручним для часто перевикористовуваних "дрібних" компонентів, таких як `FancyButton` та `MyTextInput`. Ці компоненти використовуються в додатку подібно до звичайних DOM `button` чи `input` і доступ до їхніх DOM-вузлів може бути необхідним для управління фокусом, виділенням або анімацією.
1717

18-
**Ref forwarding is an opt-in feature that lets some components take a `ref` they receive, and pass it further down (in other words, "forward" it) to a child.**
18+
**Перенаправлення рефів дає можливість певному компоненту взяти отриманий реф і передати його далі (іншими словами "перенаправити") до дочірнього компонента.**
1919

20-
In the example below, `FancyButton` uses `React.forwardRef` to obtain the `ref` passed to it, and then forward it to the DOM `button` that it renders:
20+
У прикладі нижче, `FancyButton` використовує `React.forwardRef`, щоб отримати переданий йому `ref` і перенаправити його в DOM `button`, який він рендерить:
2121

2222
`embed:forwarding-refs/fancy-button-simple-ref.js`
2323

24-
This way, components using `FancyButton` can get a ref to the underlying `button` DOM node and access it if necessary—just like if they used a DOM `button` directly.
24+
Таким чином, компоненти, що використовують `FancyButton` можуть отримати реф внутрішнього DOM-вузла `button` і якщо потрібно, мати доступ до DOM `button` подібно до того, якби він використовувався напряму.
2525

26-
Here is a step-by-step explanation of what happens in the above example:
26+
Розглянемо цей приклад покроково:
2727

28-
1. We create a [React ref](/docs/refs-and-the-dom.html) by calling `React.createRef` and assign it to a `ref` variable.
29-
1. We pass our `ref` down to `<FancyButton ref={ref}>` by specifying it as a JSX attribute.
30-
1. React passes the `ref` to the `(props, ref) => ...` function inside `forwardRef` as a second argument.
31-
1. We forward this `ref` argument down to `<button ref={ref}>` by specifying it as a JSX attribute.
32-
1. When the ref is attached, `ref.current` will point to the `<button>` DOM node.
28+
1. Ми створюємо [React-реф](/docs/refs-and-the-dom.html), викликаючи `React.createRef` і записуєм його у змінну `ref`.
29+
1. Ми передаємо наш `ref` у `<FancyButton ref={ref}>`, вказуючи його як JSX-атрибут.
30+
1. React передає `ref` у функцію `(props, ref) => ...` всередині `forwardRef` другим аргументом.
31+
1. Ми перенаправляєм аргумент `ref` далі у `<button ref={ref}>`, вказуючи його як JSX-атрибут.
32+
1. Після прив'язки рефа, `ref.current` буде вказувати на DOM-вузол `<button>`.
3333

34-
>Note
34+
>Примітка
3535
>
36-
>The second `ref` argument only exists when you define a component with `React.forwardRef` call. Regular function or class components don't receive the `ref` argument, and ref is not available in props either.
36+
>Другий аргумент `ref` існує тільки тоді, коли ви визначаєте компонент як виклик функції `React.forwardRef`. Звичайні функціональні або класові компоненти не отримують `ref` у якості аргумента чи пропса.
3737
>
38-
>Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
38+
>Перенаправлення рефів не обмежуються DOM-компонентами. Ви також можете перенаправити реф у екземпляр класового компонента.
3939
40-
## Note for component library maintainers {#note-for-component-library-maintainers}
40+
## Примітка для розробників бібліотек компонентів {#note-for-component-library-maintainers}
4141

42-
**When you start using `forwardRef` in a component library, you should treat it as a breaking change and release a new major version of your library.** This is because your library likely has an observably different behavior (such as what refs get assigned to, and what types are exported), and this can break apps and other libraries that depend on the old behavior.
42+
**Коли ви починаєте використовувати `forwardRef` у бібліотеці компонентів, ви повинні вважати це як несумісну зміну і випустити нову мажорну версію.** Причина цього в тому, що, швидше за все, компонент буде мати замітно іншу поведінку (наприклад: зміниться тип експортованих даних і елемент, до якого прив'язаний реф), в результаті чого додатки та інші бібліотеки, що покладаються на стару поведінку, перестануть працювати.
4343

44-
Conditionally applying `React.forwardRef` when it exists is also not recommended for the same reasons: it changes how your library behaves and can break your users' apps when they upgrade React itself.
44+
З цієї ж причини ми не рекомендуємо викликати `React.forwardRef` умовно (тобто перевіряючи чи функція існує). Це змінить поведінку вашої бібліотеки і додатки ваших користувачів можуть перестати працювати при оновленні версії React.
4545

46-
## Forwarding refs in higher-order components {#forwarding-refs-in-higher-order-components}
46+
## Перенаправлення рефів у компоненти вищого порядку {#forwarding-refs-in-higher-order-components}
4747

48-
This technique can also be particularly useful with [higher-order components](/docs/higher-order-components.html) (also known as HOCs). Let's start with an example HOC that logs component props to the console:
48+
Ця техніка також може бути особливо корисною у [компонентах вищого порядку](/docs/higher-order-components.html) (ще відомі, як КВП або англ. — HOC). Давайте почнемо з прикладу КВП, який виводить пропси компонента в консоль:
4949
`embed:forwarding-refs/log-props-before.js`
5050

51-
The "logProps" HOC passes all `props` through to the component it wraps, so the rendered output will be the same. For example, we can use this HOC to log all props that get passed to our "fancy button" component:
51+
КВП "logProps" передає всі `props` до компонента, який він обгортає, так що результат рендеру буде такий самий. Наприклад, ми можемо використати цей КВП, щоб вивести усі пропси передані в наш компонент `FancyButton`:
5252
`embed:forwarding-refs/fancy-button.js`
5353

54-
There is one caveat to the above example: refs will not get passed through. That's because `ref` is not a prop. Like `key`, it's handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.
54+
Щодо прикладу вище є одне застереження: тут рефи не будуть передаватись. Це тому, що `ref` не є пропом. React опрацьовує `ref` по-іншому, подібно до `key`. Якщо ви додасте реф до КВП, реф буде вказувати на зовнішній компонент-контейнер, а не на обгорнутий компонент.
5555

56-
This means that refs intended for our `FancyButton` component will actually be attached to the `LogProps` component:
56+
Це означає, що рефи призначені для компонента `FancyButton` насправді будуть прив'язані до компонента `LogProps`:
5757
`embed:forwarding-refs/fancy-button-ref.js`
5858

59-
Fortunately, we can explicitly forward refs to the inner `FancyButton` component using the `React.forwardRef` API. `React.forwardRef` accepts a render function that receives `props` and `ref` parameters and returns a React node. For example:
59+
На щастя, ми можемо явно перенаправити реф до внутрішнього компонента `FancyButton`, використовуючи `React.forwardRef` API. `React.forwardRef` приймає функцію рендеринга, яка отримує параметри `props` і `ref` та повертає React-вузол. Наприклад:
6060
`embed:forwarding-refs/log-props-after.js`
6161

62-
## Displaying a custom name in DevTools {#displaying-a-custom-name-in-devtools}
62+
## Відображення іншого імені в DevTools {#displaying-a-custom-name-in-devtools}
6363

64-
`React.forwardRef` accepts a render function. React DevTools uses this function to determine what to display for the ref forwarding component.
64+
`React.forwardRef` отримує фукнцію рендерингу. React DevTools використовує цю функцію, щоб визначити, як відображати компонент перенаправлення рефа.
6565

66-
For example, the following component will appear as "*ForwardRef*" in the DevTools:
66+
Наприклад, наступний компонент буде відображатись в DevTools, як "*ForwardRef*":
6767

6868
`embed:forwarding-refs/wrapped-component.js`
6969

70-
If you name the render function, DevTools will also include its name (e.g. "*ForwardRef(myFunction)*"):
70+
Якщо надати ім'я функції рендеринга, то воно з'явиться у назві компонента в DevTools (наприклад, "*ForwardRef(myFunction)*"):
7171

7272
`embed:forwarding-refs/wrapped-component-with-function-name.js`
7373

74-
You can even set the function's `displayName` property to include the component you're wrapping:
74+
Ви можете навіть додати властивість до функції `displayName` і вказати в ній, який саме компонент обгорнутий.
7575

7676
`embed:forwarding-refs/customized-display-name.js`

content/docs/optimizing-performance.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ brunch build -p
7171

7272
### Browserify {#browserify}
7373

74-
Для найефективнішої продакшн-збірки з використанням Brunch, встановіть декілька плагінів:
74+
Для найефективнішої продакшн-збірки з використанням Browserify, встановіть декілька плагінів:
7575

7676
```
7777
# Якщо ви користуєтесь npm

content/docs/reference-react-component.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ shouldComponentUpdate(nextProps, nextState)
258258

259259
`shouldComponentUpdate()` викликається перед рендерингом при отриманні нових пропсів і стану. За замовчуванням має значення `true`. Цей метод не викликається при першому рендері чи коли використовується `forceUpdate()`.
260260

261-
Цей метод існує лише в якості **[оптимізації продуктивності](/docs/optimizing-performance.html).** Не покладайтесь на нього, щоб "запобігти" рендерингу, оскільки це може привести до помилок. **Розгляньте можливість використая вбудованого [`PureComponent`](/docs/react-api.html#reactpurecomponent)** замість написання власного `shouldComponentUpdate()`. `PureComponent` виконує поверхове порівняння пропсів та стану і зменшує шанс того, що ви пропустите необхідне оновлення.
261+
Цей метод існує лише в якості **[оптимізації продуктивності](/docs/optimizing-performance.html).** Не покладайтесь на нього, щоб "запобігти" рендерингу, оскільки це може привести до помилок. **Розгляньте можливість використання вбудованого [`PureComponent`](/docs/react-api.html#reactpurecomponent)** замість написання власного `shouldComponentUpdate()`. `PureComponent` виконує поверхове порівняння пропсів та стану і зменшує шанс того, що ви пропустите необхідне оновлення.
262262

263263
Якщо ви впевнені, що ви хочете реалізувати його власноруч, ви можете порівняти `this.props` із `nextProps` та `this.state` із `nextState`, і повернути `false`, щоб сказати React, що це оновлення можна пропустити. Зверніть увагу на те, що повернення `false` не запобігає повторному рендерингу дочірніх компонентів, коли *їх* стан змінюється.
264264

examples/forwarding-refs/customized-display-name.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ function logProps(Component) {
77
return <LogProps {...props} forwardedRef={ref} />;
88
}
99

10-
// Give this component a more helpful display name in DevTools.
11-
// e.g. "ForwardRef(logProps(MyComponent))"
10+
// Дамо цьому компоненту більш зрозуміле ім'я в DevTools
11+
// Наприклад, "ForwardRef(logProps(MyComponent))"
1212
// highlight-range{1-2}
1313
const name = Component.displayName || Component.name;
1414
forwardRef.displayName = `logProps(${name})`;

examples/forwarding-refs/fancy-button-ref.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import FancyButton from './FancyButton';
33
// highlight-next-line
44
const ref = React.createRef();
55

6-
// The FancyButton component we imported is the LogProps HOC.
7-
// Even though the rendered output will be the same,
8-
// Our ref will point to LogProps instead of the inner FancyButton component!
9-
// This means we can't call e.g. ref.current.focus()
6+
// Компонент FancyButton, який ми імпортуємо — це КВП LogProps.
7+
// Навіть, якщо результат рендерингу буде таким же самим,
8+
// Наш реф буде вказувати на LogProps, а не на внутрішній компонент FancyButton!
9+
// Це означає, що ми, наприклад, не можемо викликати ref.current.focus()
1010
// highlight-range{4}
1111
<FancyButton
1212
label="Click Me"

examples/forwarding-refs/fancy-button-simple-ref.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ const FancyButton = React.forwardRef((props, ref) => (
55
</button>
66
));
77

8-
// You can now get a ref directly to the DOM button:
8+
// Тепер ви можете отримати реф беспосередньо на DOM button
99
const ref = React.createRef();
1010
<FancyButton ref={ref}>Click me!</FancyButton>;

examples/forwarding-refs/fancy-button.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ class FancyButton extends React.Component {
66
// ...
77
}
88

9-
// Rather than exporting FancyButton, we export LogProps.
10-
// It will render a FancyButton though.
9+
// Замість того, щоб експортувати FancyButton, ми експортуємо LogProps.
10+
// При цьому рендеритись буде FancyButton.
1111
// highlight-next-line
1212
export default logProps(FancyButton);

examples/forwarding-refs/log-props-after.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@ function logProps(Component) {
99
// highlight-next-line
1010
const {forwardedRef, ...rest} = this.props;
1111

12-
// Assign the custom prop "forwardedRef" as a ref
12+
// Передаємо в якості рефа проп "forwardedRef"
1313
// highlight-next-line
1414
return <Component ref={forwardedRef} {...rest} />;
1515
}
1616
}
1717

18-
// Note the second param "ref" provided by React.forwardRef.
19-
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
20-
// And it can then be attached to the Component.
18+
// Зауважте, другий параметр "ref" переданий від React.forwardRef.
19+
// Ми можемо передати його в LogProps, як звичайний проп, наприклад: "forwardedRef",
20+
// А потім прив'язати його до компоненту.
2121
// highlight-range{1-3}
2222
return React.forwardRef((props, ref) => {
2323
return <LogProps {...props} forwardedRef={ref} />;

0 commit comments

Comments
 (0)