Skip to content

Commit 72cc366

Browse files
authored
Merge pull request #592 from MaksymMohyla/maksym-mohyla-translation
Translated useImperativeHandlePage
2 parents 6a9521f + 6b4aa4e commit 72cc366

File tree

1 file changed

+31
-31
lines changed

1 file changed

+31
-31
lines changed

src/content/reference/react/useImperativeHandle.md

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useImperativeHandle
44

55
<Intro>
66

7-
`useImperativeHandle` is a React Hook that lets you customize the handle exposed as a [ref.](/learn/manipulating-the-dom-with-refs)
7+
`useImperativeHandle` — це хук, який дає змогу налаштовувати дескриптор (handle) публічно доступного [рефа.](/learn/manipulating-the-dom-with-refs)
88

99
```js
1010
useImperativeHandle(ref, createHandle, dependencies?)
@@ -16,77 +16,77 @@ useImperativeHandle(ref, createHandle, dependencies?)
1616
1717
---
1818
19-
## Reference {/*reference*/}
19+
## Опис {/*reference*/}
2020
2121
### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}
2222
23-
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
23+
Викличте `useImperativeHandle` на верхньому рівні вашого компонента, щоб налаштувати дескриптор рефа, доступного з нього:
2424
2525
```js
2626
import { useImperativeHandle } from 'react';
2727

2828
function MyInput({ ref }) {
2929
useImperativeHandle(ref, () => {
3030
return {
31-
// ... your methods ...
31+
// ... ваші методи ...
3232
};
3333
}, []);
3434
// ...
3535
```
3636
37-
[See more examples below.](#usage)
37+
[Перегляньте більше прикладів нижче.](#usage)
3838
39-
#### Parameters {/*parameters*/}
39+
#### Параметри {/*parameters*/}
4040
41-
* `ref`: The `ref` you received as a prop to the `MyInput` component.
41+
* `ref`: `ref`, який ви отримали як проп у компоненті `MyInput`.
4242
43-
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. That ref handle can have any type. Usually, you will return an object with the methods you want to expose.
43+
* `createHandle`: Функція, яка не приймає аргументів і повертає дескриптор рефа, до якого ви хочете надати доступ. Дескриптор може бути будь-якого типу. Зазвичай, ви повертатимете об'єкт із методами, до яких ви хочете надати доступ.
4444
45-
* **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If a re-render resulted in a change to some dependency, or if you omitted this argument, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
45+
* **Опційний параметр** `dependencies`: Список усіх реактивних значень, на які посилається код `createHandle`. Реактивні значення охоплюють пропси, стан і всі змінні та функції, оголошені безпосередньо в тілі компонента. Якщо ваш лінтер [налаштований для React](/learn/editor-setup#linting), він перевірить, чи кожне реактивне значення вказане як залежність. Список залежностей повинен містити стале число елементів, записаних у рядок як `[залежність1, залежність2, залежність3]`. React порівняє кожну залежність із своїм попереднім значенням, використовуючи функцію [`Object.is`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Якщо повторний рендер призвів до зміни однієї із залежностей або якщо ви пропустили даний аргумент, ваша функція `createHandle` виконуватиметься повторно, і новостворений дескриптор буде призначений рефу.
4646
4747
<Note>
4848
49-
Starting with React 19, [`ref` is available as a prop.](/blog/2024/12/05/react-19#ref-as-a-prop) In React 18 and earlier, it was necessary to get the `ref` from [`forwardRef`.](/reference/react/forwardRef)
49+
Починаючи з React 19, [`ref` доступний як проп.](/blog/2024/12/05/react-19#ref-as-a-prop) У React 18 і старіших версіях необхідно було отримувати `ref` із [`forwardRef`.](/reference/react/forwardRef)
5050
5151
</Note>
5252
53-
#### Returns {/*returns*/}
53+
#### Результат {/*returns*/}
5454
55-
`useImperativeHandle` returns `undefined`.
55+
`useImperativeHandle` повертає `undefined`.
5656
5757
---
5858
59-
## Usage {/*usage*/}
59+
## Використання {/*usage*/}
6060
61-
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
61+
### Доступ батьківського елемента до налаштованого дескриптора рефа {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
6262
63-
To expose a DOM node to the parent element, pass in the `ref` prop to the node.
63+
Щоб надати доступ до DOM-вузла батьківському елементу, передайте проп `ref` далі до цього вузла.
6464
6565
```js {2}
6666
function MyInput({ ref }) {
6767
return <input ref={ref} />;
6868
};
6969
```
7070
71-
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](/learn/manipulating-the-dom-with-refs) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
71+
У коді вище [реф, переданий компоненту `MyInput`, отримає DOM-вузол `<input>`.](/learn/manipulating-the-dom-with-refs) Однак, замість цього ви можете задати власне значення. Щоб налаштувати публічний дескриптор, викличте `useImperativeHandle` на верхньому рівні вашого компонента:
7272
7373
```js {4-8}
7474
import { useImperativeHandle } from 'react';
7575

7676
function MyInput({ ref }) {
7777
useImperativeHandle(ref, () => {
7878
return {
79-
// ... your methods ...
79+
// ... ваші методи ...
8080
};
8181
}, []);
8282

8383
return <input />;
8484
};
8585
```
8686
87-
Note that in the code above, the `ref` is no longer passed to the `<input>`.
87+
Зверніть увагу, що в наведеному вище коді `ref` більше не передається елементу `<input>`.
8888
89-
For example, suppose you don't want to expose the entire `<input>` DOM node, but you want to expose two of its methods: `focus` and `scrollIntoView`. To do this, keep the real browser DOM in a separate ref. Then use `useImperativeHandle` to expose a handle with only the methods that you want the parent component to call:
89+
Наприклад, припустимо, що ви не хочете робити публічним весь DOM-вузол `<input>`, а лише два його методи: `focus` і `scrollIntoView`. У цьому разі зберігайте справжній браузерний DOM в окремому рефі. Потім викличте `useImperativeHandle`, щоб надати доступ до дескриптора, який містить лише методи, необхідні для виклику батьківським компонентом:
9090
9191
```js {7-14}
9292
import { useRef, useImperativeHandle } from 'react';
@@ -109,7 +109,7 @@ function MyInput({ ref }) {
109109
};
110110
```
111111
112-
Now, if the parent component gets a ref to `MyInput`, it will be able to call the `focus` and `scrollIntoView` methods on it. However, it will not have full access to the underlying `<input>` DOM node.
112+
Тепер якщо батьківський компонент передасть реф до `MyInput`, він зможе викликати його методи `focus` і `scrollIntoView`. Однак, він не буде мати повного доступу до справжнього DOM-вузла `<input>`.
113113
114114
<Sandpack>
115115
@@ -122,15 +122,15 @@ export default function Form() {
122122

123123
function handleClick() {
124124
ref.current.focus();
125-
// This won't work because the DOM node isn't exposed:
125+
// Це не спрацює, бо вузол DOM не публічний:
126126
// ref.current.style.opacity = 0.5;
127127
}
128128

129129
return (
130130
<form>
131-
<MyInput placeholder="Enter your name" ref={ref} />
131+
<MyInput placeholder="Введіть ваше ім'я" ref={ref} />
132132
<button type="button" onClick={handleClick}>
133-
Edit
133+
Редагувати
134134
</button>
135135
</form>
136136
);
@@ -170,9 +170,9 @@ input {
170170
171171
---
172172
173-
### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
173+
### Надання доступу до власних імперативних методів {/*exposing-your-own-imperative-methods*/}
174174
175-
The methods you expose via an imperative handle don't have to match the DOM methods exactly. For example, this `Post` component exposes a `scrollAndFocusAddComment` method via an imperative handle. This lets the parent `Page` scroll the list of comments *and* focus the input field when you click the button:
175+
Методи, які ви передаєте через імперативний дескриптор, не обов'язково мають точно збігатися з DOM-методами. Наприклад, цей компонент `Post` передає метод `scrollAndFocusAddComment` через дескриптор. Це дає батьківському компоненту `Page` змогу прогорнути список коментарів *і* фокусувати поле введення, коли ви натискаєте кнопку:
176176
177177
<Sandpack>
178178
@@ -190,7 +190,7 @@ export default function Page() {
190190
return (
191191
<>
192192
<button onClick={handleClick}>
193-
Write a comment
193+
Написати коментар
194194
</button>
195195
<Post ref={postRef} />
196196
</>
@@ -219,7 +219,7 @@ function Post({ ref }) {
219219
return (
220220
<>
221221
<article>
222-
<p>Welcome to my blog!</p>
222+
<p>Вітаю в моєму блозі!</p>
223223
</article>
224224
<CommentList ref={commentsRef} />
225225
<AddComment ref={addCommentRef} />
@@ -248,7 +248,7 @@ function CommentList({ ref }) {
248248

249249
let comments = [];
250250
for (let i = 0; i < 50; i++) {
251-
comments.push(<p key={i}>Comment #{i}</p>);
251+
comments.push(<p key={i}>Коментар #{i}</p>);
252252
}
253253

254254
return (
@@ -265,7 +265,7 @@ export default CommentList;
265265
import { useRef, useImperativeHandle } from 'react';
266266

267267
function AddComment({ ref }) {
268-
return <input placeholder="Add comment..." ref={ref} />;
268+
return <input placeholder="Додати коментар..." ref={ref} />;
269269
}
270270

271271
export default AddComment;
@@ -285,8 +285,8 @@ export default AddComment;
285285
286286
<Pitfall>
287287
288-
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
288+
**Не зловживайте рефами.** Використовуйте рефи лише для *імперативної* поведінки, яку ви не можете виразити через пропси: наприклад, прогортування до вузла DOM, фокусування вузла, виклик анімації, виділення тексту тощо.
289289
290-
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
290+
**Якщо ви можете виразити щось як проп, тоді не варто використовувати реф.** Наприклад, замість передавання імперативного дескриптора як `{ open, close }` із компонента `Modal`, краще використати проп `isOpen` як `<Modal isOpen={isOpen} />`. [Ефекти](/learn/synchronizing-with-effects) можуть допомогти вам надати доступ до імперативних частин через пропси.
291291
292292
</Pitfall>

0 commit comments

Comments
 (0)