diff --git a/src/content/reference/react/forwardRef.md b/src/content/reference/react/forwardRef.md index 5b0e679b89..da23b50b16 100644 --- a/src/content/reference/react/forwardRef.md +++ b/src/content/reference/react/forwardRef.md @@ -1,18 +1,17 @@ --- title: forwardRef --- - -In React 19, `forwardRef` is no longer necessary. Pass `ref` as a prop instead. +В React 19 `forwardRef` больше не нужен. Вместо этого передавайте `ref` как пропс. -`forwardRef` will deprecated in a future release. Learn more [here](/blog/2024/04/25/react-19#ref-as-a-prop). +`forwardRef` будет устаревшим в будущем релизе. Узнайте больше [здесь](/blog/2024/04/25/react-19#ref-as-a-prop). -`forwardRef` lets your component expose a DOM node to parent component with a [ref.](/learn/manipulating-the-dom-with-refs) +`forwardRef` позволяет вашему компоненту предоставить DOM-узел родительскому компоненту с помощью [ref.](/learn/manipulating-the-dom-with-refs) ```js const SomeComponent = forwardRef(render) @@ -24,11 +23,11 @@ const SomeComponent = forwardRef(render) --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `forwardRef(render)` {/*forwardref*/} -Call `forwardRef()` to let your component receive a ref and forward it to a child component: +Вызовите `forwardRef()`, чтобы ваш компонент мог принимать ref и передавать его дочернему компоненту: ```js import { forwardRef } from 'react'; @@ -38,26 +37,26 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*parameters*/} +#### Параметры {/*parameters*/} -* `render`: The render function for your component. React calls this function with the props and `ref` that your component received from its parent. The JSX you return will be the output of your component. +* `render`: Функция рендеринга для вашего компонента. React вызывает эту функцию с пропсами и `ref`, которые ваш компонент получил от родителя. Возвращаемый вами JSX будет результатом работы вашего компонента. -#### Returns {/*returns*/} +#### Возвращает {/*returns*/} -`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by `forwardRef` is also able to receive a `ref` prop. +`forwardRef` возвращает React-компонент, который вы можете рендерить в JSX. В отличие от React-компонентов, определённых как обычные функции, компонент, возвращаемый `forwardRef`, также способен принимать пропс `ref`. -#### Caveats {/*caveats*/} +#### Особенности {/*caveats*/} -* In Strict Mode, React will **call your render function twice** in order to [help you find accidental impurities.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored. +* В Strict Mode React **дважды вызовет вашу функцию рендеринга**, чтобы [помочь вам найти случайные примеси.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) Это поведение только для разработки и не влияет на продакшен. Если ваша функция рендеринга является чистой (как и должно быть), это не должно повлиять на логику вашего компонента. Результат одного из вызовов будет проигнорирован. --- -### `render` function {/*render-function*/} +### Функция `render` {/*render-function*/} -`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`: +`forwardRef` принимает функцию рендеринга в качестве аргумента. React вызывает эту функцию с `props` и `ref`: ```js const MyInput = forwardRef(function MyInput(props, ref) { @@ -70,23 +69,23 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -#### Parameters {/*render-parameters*/} +#### Параметры {/*render-parameters*/} -* `props`: The props passed by the parent component. +* `props`: Пропсы, переданные родительским компонентом. -* `ref`: The `ref` attribute passed by the parent component. The `ref` can be an object or a function. If the parent component has not passed a ref, it will be `null`. You should either pass the `ref` you receive to another component, or pass it to [`useImperativeHandle`.](/reference/react/useImperativeHandle) +* `ref`: Атрибут `ref`, переданный родительским компонентом. `ref` может быть объектом или функцией. Если родительский компонент не передал ref, он будет `null`. Вы должны либо передать полученный `ref` другому компоненту, либо передать его в [`useImperativeHandle`.](/reference/react/useImperativeHandle) -#### Returns {/*render-returns*/} +#### Возвращает {/*render-returns*/} -`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by `forwardRef` is able to take a `ref` prop. +`forwardRef` возвращает React-компонент, который вы можете рендерить в JSX. В отличие от React-компонентов, определённых как обычные функции, компонент, возвращаемый `forwardRef`, способен принимать пропс `ref`. --- -## Usage {/*usage*/} +## Использование {/*usage*/} -### Exposing a DOM node to the parent component {/*exposing-a-dom-node-to-the-parent-component*/} +### Предоставление DOM-узла родительскому компоненту {/*exposing-a-dom-node-to-the-parent-component*/} -By default, each component's DOM nodes are private. However, sometimes it's useful to expose a DOM node to the parent--for example, to allow focusing it. To opt in, wrap your component definition into `forwardRef()`: +По умолчанию DOM-узлы каждого компонента являются приватными. Однако иногда бывает полезно предоставить DOM-узел родителю — например, чтобы позволить ему сфокусироваться на нём. Чтобы включить эту возможность, оберните определение вашего компонента в `forwardRef()`: ```js {3,11} import { forwardRef } from 'react'; @@ -102,7 +101,7 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -You will receive a ref as the second argument after props. Pass it to the DOM node that you want to expose: +Вы получите ref как второй аргумент после пропсов. Передайте его DOM-узлу, который вы хотите предоставить: ```js {8} [[1, 3, "ref"], [1, 8, "ref", 30]] import { forwardRef } from 'react'; @@ -118,7 +117,7 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -This lets the parent `Form` component access the `` DOM node exposed by `MyInput`: +Это позволяет родительскому компоненту `Form` получить доступ к DOM-узлу ``, предоставленному `MyInput`: ```js [[1, 2, "ref"], [1, 10, "ref", 41], [2, 5, "ref.current"]] function Form() { @@ -139,15 +138,15 @@ function Form() { } ``` -This `Form` component [passes a ref](/reference/react/useRef#manipulating-the-dom-with-a-ref) to `MyInput`. The `MyInput` component *forwards* that ref to the `` browser tag. As a result, the `Form` component can access that `` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it. +Этот компонент `Form` [передаёт ref](/reference/react/useRef#manipulating-the-dom-with-a-ref) в `MyInput`. Компонент `MyInput` *перенаправляет* этот ref в браузерный тег ``. В результате компонент `Form` может получить доступ к этому DOM-узлу `` и вызвать на нём [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus). -Keep in mind that exposing a ref to the DOM node inside your component makes it harder to change your component's internals later. You will typically expose DOM nodes from reusable low-level components like buttons or text inputs, but you won't do it for application-level components like an avatar or a comment. +Имейте в виду, что предоставление ref к DOM-узлу внутри вашего компонента затрудняет изменение внутренних данных вашего компонента в будущем. Обычно вы будете предоставлять DOM-узлы из повторно используемых низкоуровневых компонентов, таких как кнопки или текстовые поля ввода, но не для компонентов уровня приложения, таких как аватар или комментарий. - + -#### Focusing a text input {/*focusing-a-text-input*/} +#### Фокусировка текстового поля ввода {/*focusing-a-text-input*/} -Clicking the button will focus the input. The `Form` component defines a ref and passes it to the `MyInput` component. The `MyInput` component forwards that ref to the browser ``. This lets the `Form` component focus the ``. +Нажатие на кнопку сфокусирует поле ввода. Компонент `Form` определяет ref и передаёт его компоненту `MyInput`. Компонент `MyInput` перенаправляет этот ref в браузерное поле ввода ``. Это позволяет компоненту `Form` сфокусироваться на ``. @@ -199,9 +198,9 @@ input { -#### Playing and pausing a video {/*playing-and-pausing-a-video*/} +#### Воспроизведение и пауза видео {/*playing-and-pausing-a-video*/} -Clicking the button will call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on a `