diff --git a/content/docs/forwarding-refs.md b/content/docs/forwarding-refs.md index 3318d8499..461e697f4 100644 --- a/content/docs/forwarding-refs.md +++ b/content/docs/forwarding-refs.md @@ -1,76 +1,75 @@ --- id: forwarding-refs -title: Forwarding Refs +title: Перенаправление рефов permalink: docs/forwarding-refs.html --- -Ref forwarding is a technique for automatically passing a [ref](/docs/refs-and-the-dom.html) through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below. +Перенаправление рефов позволяет автоматически передавать [реф](/docs/refs-and-the-dom.html) компонента одному из его дочерних элементов. Большинству компонентов перенаправление рефов не нужно, но оно может быть полезно, например, если вы пишете библиотеку. Рассмотрим наиболее частые сценарии. -## Forwarding refs to DOM components {#forwarding-refs-to-dom-components} +## Перенаправление рефов в DOM-компоненты {#forwarding-refs-to-dom-components} -Consider a `FancyButton` component that renders the native `button` DOM element: +Допустим, у нас есть компонент `FancyButton`, который рендерит нативный DOM-элемент `button`: `embed:forwarding-refs/fancy-button-simple.js` -React components hide their implementation details, including their rendered output. Other components using `FancyButton` **usually will not need to** [obtain a ref](/docs/refs-and-the-dom.html) to the inner `button` DOM element. This is good because it prevents components from relying on each other's DOM structure too much. +React-компоненты скрывают свои детали реализации, в том числе результат рендеринга. Реф элемента `button` из `FancyButton` **обычно и не требуется** другим компонентам. Это хорошо, поскольку такой подход не даёт компонентам излишне полагаться на структуру DOM друг друга. -Although such encapsulation is desirable for application-level components like `FeedStory` or `Comment`, it can be inconvenient for highly reusable "leaf" components like `FancyButton` or `MyTextInput`. These components tend to be used throughout the application in a similar manner as a regular DOM `button` and `input`, and accessing their DOM nodes may be unavoidable for managing focus, selection, or animations. +Такая инкапсуляция хорошо подходит компонентам, которые описывают некую законченную часть приложения, например, `FeedStory` или `Comment`. А вот в «маленьких», часто переиспользуемых компонентах, таких как `FancyButton` или `MyTextInput`, она может быть неудобной. Чтобы управлять фокусом, выделением и анимациями этих компонентов, придётся получить доступ к их DOM-узлам. -**Ref forwarding is an opt-in feature that lets some components take a `ref` they receive, and pass it further down (in other words, "forward" it) to a child.** +**Перенаправление рефов позволяет взять `ref` из атрибутов компонента, и передать («перенаправить») его одному из дочерних компонентов.** -In the example below, `FancyButton` uses `React.forwardRef` to obtain the `ref` passed to it, and then forward it to the DOM `button` that it renders: +В данном примере мы используем `React.forwardRef` в компоненте `FancyButton`, чтобы получить реф и передать его в дочерний DOM-элемент `button`. `embed:forwarding-refs/fancy-button-simple-ref.js` -This way, components using `FancyButton` can get a ref to the underlying `button` DOM node and access it if necessary—just like if they used a DOM `button` directly. +Таким образом, когда мы будем применять `FancyButton` в других компонентах, мы сможем получить реф находящегося в нём DOM-узла `button` и использовать его так же, как если бы мы рендерили непосредственно `button`. -Here is a step-by-step explanation of what happens in the above example: +Рассмотрим этот пример пошагово: -1. We create a [React ref](/docs/refs-and-the-dom.html) by calling `React.createRef` and assign it to a `ref` variable. -1. We pass our `ref` down to `` by specifying it as a JSX attribute. -1. React passes the `ref` to the `(props, ref) => ...` function inside `forwardRef` as a second argument. -1. We forward this `ref` argument down to ` )); -// You can now get a ref directly to the DOM button: +// Теперь реф будет указывать непосредственно на DOM-узел button: const ref = React.createRef(); Click me!; diff --git a/examples/forwarding-refs/fancy-button.js b/examples/forwarding-refs/fancy-button.js index 9dcd13e16..825d56bdd 100644 --- a/examples/forwarding-refs/fancy-button.js +++ b/examples/forwarding-refs/fancy-button.js @@ -6,7 +6,7 @@ class FancyButton extends React.Component { // ... } -// Rather than exporting FancyButton, we export LogProps. -// It will render a FancyButton though. +// Вместо экспорта FancyButton, мы экспортируем LogProps. +// Рендериться при этом будет FancyButton. // highlight-next-line export default logProps(FancyButton); diff --git a/examples/forwarding-refs/log-props-after.js b/examples/forwarding-refs/log-props-after.js index a603bd697..4ccfc99a9 100644 --- a/examples/forwarding-refs/log-props-after.js +++ b/examples/forwarding-refs/log-props-after.js @@ -9,15 +9,15 @@ function logProps(Component) { // highlight-next-line const {forwardedRef, ...rest} = this.props; - // Assign the custom prop "forwardedRef" as a ref + // Передаём в качестве рефа проп "forwardedRef" // highlight-next-line return ; } } - // Note the second param "ref" provided by React.forwardRef. - // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef" - // And it can then be attached to the Component. + // Обратите внимание, что React.forwardRef передает "ref" вторым аргументом. + // Мы можем передать его дальше как проп, например, "forwardedRef", + // а потом привязать его к компоненту. // highlight-range{1-3} return React.forwardRef((props, ref) => { return ; diff --git a/examples/forwarding-refs/log-props-before.js b/examples/forwarding-refs/log-props-before.js index a507e818b..5d384bf74 100644 --- a/examples/forwarding-refs/log-props-before.js +++ b/examples/forwarding-refs/log-props-before.js @@ -2,8 +2,8 @@ function logProps(WrappedComponent) { class LogProps extends React.Component { componentDidUpdate(prevProps) { - console.log('old props:', prevProps); - console.log('new props:', this.props); + console.log('старые пропсы:', prevProps); + console.log('новые пропсы:', this.props); } render() {