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), он проверит, что каждое реактивное значение правильно указано как зависимость. Список зависимостей должен иметь постоянное количество элементов и быть написан в строке, например `[dep1, dep2, dep3]`. React будет сравнивать каждую зависимость с её предыдущим значением с помощью [`Object.is`](https://developer.mozilla.org/en-US/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*/}
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,7 +122,7 @@ 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
@@ -170,9 +170,9 @@ input {
170
170
171
171
---
172
172
173
-
### 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
@@ -285,8 +285,8 @@ export default AddComment;
285
285
286
286
<Pitfall>
287
287
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
+
**Не злоупотребляйте рефами.** Используйте рефы только для *императивных* действий, которые вы не можете выразить через пропсы: например, прокрутка к узлу, фокусировка на узле, запуск анимации, выделение текста и т. д.
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