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
Call`useImperativeHandle`at the top level of your component to customize the ref handle it exposes:
23
+
Викличте`useImperativeHandle`на верхньому рівні вашого компонента, щоб налаштувати дескриптор рефа, доступного з нього:
24
24
25
25
```js
26
26
import { useImperativeHandle } from'react';
27
27
28
28
functionMyInput({ ref }) {
29
29
useImperativeHandle(ref, () => {
30
30
return {
31
-
// ... your methods ...
31
+
// ... ваші методи ...
32
32
};
33
33
}, []);
34
34
// ...
35
35
```
36
36
37
-
[See more examples below.](#usage)
37
+
[Перегляньте більше прикладів нижче.](#usage)
38
38
39
-
#### Parameters {/*parameters*/}
39
+
#### Параметри {/*parameters*/}
40
40
41
-
* `ref`: The `ref` you received as a prop to the`MyInput` component.
41
+
* `ref`: `ref`, який ви отримали як проп у компоненті`MyInput`.
42
42
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`: Функція, яка не приймає аргументів і повертає дескриптор рефа, до якого ви хочете надати доступ. Дескриптор може бути будь-якого типу. Зазвичай, ви повертатимете об'єкт із методами, до яких ви хочете надати доступ.
44
44
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` виконуватиметься повторно, і новостворений дескриптор буде призначений рефу.
46
46
47
47
<Note>
48
48
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)
50
50
51
51
</Note>
52
52
53
-
#### Returns {/*returns*/}
53
+
#### Результат {/*returns*/}
54
54
55
-
`useImperativeHandle`returns`undefined`.
55
+
`useImperativeHandle`повертає`undefined`.
56
56
57
57
---
58
58
59
-
## Usage {/*usage*/}
59
+
## Використання {/*usage*/}
60
60
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*/}
62
62
63
-
To expose a DOM node to the parent element, pass in the `ref`prop to the node.
63
+
Щоб надати доступ до DOM-вузла батьківському елементу, передайте проп `ref`далі до цього вузла.
64
64
65
65
```js {2}
66
66
functionMyInput({ ref }) {
67
67
return<input ref={ref} />;
68
68
};
69
69
```
70
70
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`на верхньому рівні вашого компонента:
72
72
73
73
```js {4-8}
74
74
import { useImperativeHandle } from'react';
75
75
76
76
functionMyInput({ ref }) {
77
77
useImperativeHandle(ref, () => {
78
78
return {
79
-
// ... your methods ...
79
+
// ... ваші методи ...
80
80
};
81
81
}, []);
82
82
83
83
return<input />;
84
84
};
85
85
```
86
86
87
-
Note that in the code above, the`ref`is no longer passed to the`<input>`.
87
+
Зверніть увагу, що в наведеному вище коді`ref`більше не передається елементу`<input>`.
88
88
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`, щоб надати доступ до дескриптора, який містить лише методи, необхідні для виклику батьківським компонентом:
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>`.
113
113
114
114
<Sandpack>
115
115
@@ -122,15 +122,15 @@ export default function Form() {
122
122
123
123
functionhandleClick() {
124
124
ref.current.focus();
125
-
//This won't work because the DOM node isn't exposed:
125
+
//Це не спрацює, бо вузол DOM не публічний:
126
126
// ref.current.style.opacity = 0.5;
127
127
}
128
128
129
129
return (
130
130
<form>
131
-
<MyInput placeholder="Enter your name" ref={ref} />
### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
173
+
### Надання доступу до власних імперативних методів {/*exposing-your-own-imperative-methods*/}
174
174
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`змогу прогорнути список коментарів *і* фокусувати поле введення, коли ви натискаєте кнопку:
176
176
177
177
<Sandpack>
178
178
@@ -190,7 +190,7 @@ export default function Page() {
190
190
return (
191
191
<>
192
192
<button onClick={handleClick}>
193
-
Write a comment
193
+
Написати коментар
194
194
</button>
195
195
<Post ref={postRef} />
196
196
</>
@@ -219,7 +219,7 @@ function Post({ ref }) {
219
219
return (
220
220
<>
221
221
<article>
222
-
<p>Welcome to my blog!</p>
222
+
<p>Вітаю в моєму блозі!</p>
223
223
</article>
224
224
<CommentList ref={commentsRef} />
225
225
<AddComment ref={addCommentRef} />
@@ -248,7 +248,7 @@ function CommentList({ ref }) {
**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, фокусування вузла, виклик анімації, виділення тексту тощо.
289
289
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) можуть допомогти вам надати доступ до імперативних частин через пропси.
0 commit comments