Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions src/content/reference/react/useImperativeHandle.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: useImperativeHandle

<Intro>

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

```js
useImperativeHandle(ref, createHandle, dependencies?)
Expand All @@ -16,77 +16,77 @@ useImperativeHandle(ref, createHandle, dependencies?)

---

## Reference {/*reference*/}
## Справочник {/*reference*/}

### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}

Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
Вызовите `useImperativeHandle` на верхнем уровне вашего компонента, чтобы настроить обработчик рефа, который он предоставляет:

```js
import { useImperativeHandle } from 'react';

function MyInput({ ref }) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
// ... ваши методы ...
};
}, []);
// ...
```

[See more examples below.](#usage)
[См. больше примеров ниже.](#usage)

#### Parameters {/*parameters*/}
#### Параметры {/*parameters*/}

* `ref`: The `ref` you received as a prop to the `MyInput` component.
* `ref`: `ref`, который вы получили как пропс компонента `MyInput`.

* `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.
* `createHandle`: Функция, которая не принимает аргументов и возвращает обработчик рефа, который вы хотите предоставить. Этот обработчик рефа может иметь любой тип. Обычно вы будете возвращать объект с методами, которые хотите предоставить.

* **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.
* **необязательный** `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` будет выполнена повторно, и новый обработчик будет назначен рефу.

<Note>

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)
Начиная с React 19, [`ref` доступен как пропс.](/blog/2024/12/05/react-19#ref-as-a-prop) В React 18 и более ранних версиях было необходимо получить `ref` из [`forwardRef`.](/reference/react/forwardRef)

</Note>

#### Returns {/*returns*/}
#### Возвращает {/*returns*/}

`useImperativeHandle` returns `undefined`.
`useImperativeHandle` возвращает `undefined`.

---

## Usage {/*usage*/}
## Использование {/*usage*/}

### Exposing a custom ref handle to the parent component {/*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.
Чтобы предоставить DOM-узел родительскому элементу, передайте пропс `ref` этому узлу.

```js {2}
function MyInput({ ref }) {
return <input ref={ref} />;
};
```

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:
С помощью кода выше, [реф к `MyInput` получит DOM-узел `<input>`.](/learn/manipulating-the-dom-with-refs) Однако вы можете предоставить вместо него пользовательское значение. Чтобы настроить предоставляемый обработчик, вызовите `useImperativeHandle` на верхнем уровне вашего компонента:

```js {4-8}
import { useImperativeHandle } from 'react';

function MyInput({ ref }) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
// ... ваши методы ...
};
}, []);

return <input />;
};
```

Note that in the code above, the `ref` is no longer passed to the `<input>`.
Обратите внимание, что в коде выше `ref` больше не передается в `<input>`.

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:
Например, предположим, вы не хотите предоставлять весь DOM-узел `<input>`, но хотите предоставить два его метода: `focus` и `scrollIntoView`. Для этого сохраните реальный DOM браузера в отдельном рефе. Затем используйте `useImperativeHandle`, чтобы предоставить обработчик только с теми методами, которые вы хотите, чтобы родительский компонент мог вызывать:

```js {7-14}
import { useRef, useImperativeHandle } from 'react';
Expand All @@ -109,7 +109,7 @@ function MyInput({ ref }) {
};
```

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.
Теперь, если родительский компонент получит реф к `MyInput`, он сможет вызывать методы `focus` и `scrollIntoView` на нем. Однако он не будет иметь полного доступа к нижележащему DOM-узлу `<input>`.

<Sandpack>

Expand All @@ -122,7 +122,7 @@ export default function Form() {

function handleClick() {
ref.current.focus();
// This won't work because the DOM node isn't exposed:
// Это не сработает, потому что DOM-узел не предоставлен:
// ref.current.style.opacity = 0.5;
}

Expand Down Expand Up @@ -170,9 +170,9 @@ input {

---

### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
### Предоставление собственных императивных методов {/*exposing-your-own-imperative-methods*/}

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:
Методы, которые вы предоставляете через императивный обработчик, не обязательно должны точно совпадать с методами DOM. Например, этот компонент `Post` предоставляет метод `scrollAndFocusAddComment` через императивный обработчик. Это позволяет родительскому компоненту `Page` прокрутить список комментариев *и* сфокусироваться на поле ввода при нажатии кнопки:

<Sandpack>

Expand Down Expand Up @@ -285,8 +285,8 @@ export default AddComment;

<Pitfall>

**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.
**Не злоупотребляйте рефами.** Используйте рефы только для *императивных* действий, которые вы не можете выразить через пропсы: например, прокрутка к узлу, фокусировка на узле, запуск анимации, выделение текста и т. д.

**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.
**Если вы можете выразить что-то через пропс, вы не должны использовать реф.** Например, вместо предоставления императивного обработчика вроде `{ open, close }` из компонента `Modal`, лучше принять `isOpen` как пропс, например `<Modal isOpen={isOpen} />`. [Эффекты](/learn/synchronizing-with-effects) могут помочь вам предоставить императивное поведение через пропсы.

</Pitfall>
</Pitfall>
Loading