From 7fbfa56141cbf810e8793a7fcbae83e8291c1114 Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Sat, 16 Feb 2019 12:30:07 +0400 Subject: [PATCH 01/52] =?UTF-8?q?=D0=92=D0=B7=D0=B0=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D1=81=D1=82=D0=B2=D0=B8=D0=B5=20=D1=81=D0=BE=20?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D1=80=D0=BE=D0=BD=D0=BD=D0=B8=D0=BC=D0=B8=20?= =?UTF-8?q?=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=D0=B0?= =?UTF-8?q?=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/integrating-with-other-libraries.md | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 18a67c457..c9c190993 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -1,26 +1,26 @@ --- -id: integrating-with-other-libraries +id: Взаимодествие со сторонними библиотеками title: Integrating with Other Libraries permalink: docs/integrating-with-other-libraries.html --- -React can be used in any web application. It can be embedded in other applications and, with a little care, other applications can be embedded in React. This guide will examine some of the more common use cases, focusing on integration with [jQuery](https://jquery.com/) and [Backbone](http://backbonejs.org/), but the same ideas can be applied to integrating components with any existing code. +React может использоваться в любом веб-приложении. Он может быть встроен в другие приложения, и с некоторыми оговорками другие приложения могут встраиваться в React. Это руководство рассматривает некоторые общие случаи, с упором на интеграцию с [jQuery](https://jquery.com/) и [Backbone](http://backbonejs.org). Те же подходы могут использоваться для интеграции компонентов с любым существующим кодом. -## Integrating with DOM Manipulation Plugins {#integrating-with-dom-manipulation-plugins} +## Интеграция с плагинами, изменяющими DOM {#integrating-with-dom-manipulation-plugins} -React is unaware of changes made to the DOM outside of React. It determines updates based on its own internal representation, and if the same DOM nodes are manipulated by another library, React gets confused and has no way to recover. +React не значет об изменениях DOM, которые сделаны вне React. Он определяет обновления на основе своего внутреннего представления, и изменение тех же DOM узлов другими библиотеками сбивает React c толку. -This does not mean it is impossible or even necessarily difficult to combine React with other ways of affecting the DOM, you just have to be mindful of what each is doing. +Это не означает, что соединить React с другими инструментами работы с DOM сложно или невозможно. Просто нужно помнить, за что отвечает каждый инструмент. -The easiest way to avoid conflicts is to prevent the React component from updating. You can do this by rendering elements that React has no reason to update, like an empty `
`. +Самый простой способ избежать конфликтов -- предотвратить обновление React компонента. Это можно сделать отрендерив элемент, который не должен обновляться React, например пустой `
`. -### How to Approach the Problem {#how-to-approach-the-problem} +### Как подступиться к проблеме {#how-to-approach-the-problem} -To demonstrate this, let's sketch out a wrapper for a generic jQuery plugin. +Для демонстрации давайте набросаем обертку вокруг обобщенного jQuery плагина. -We will attach a [ref](/docs/refs-and-the-dom.html) to the root DOM element. Inside `componentDidMount`, we will get a reference to it so we can pass it to the jQuery plugin. +Мы установим [реф](/docs/refs-and-the-dom.html) на корневой DOM-элемент. Внутри `componentDidMount` мы получим ссылку и передадим ее в jQuery плагин. -To prevent React from touching the DOM after mounting, we will return an empty `
` from the `render()` method. The `
` element has no properties or children, so React has no reason to update it, leaving the jQuery plugin free to manage that part of the DOM: +Чтобы React не трогал DOM после монтирования, мы вернем пустой `
` из метода `render()`. Элемент `
` не имеет ни свойств, ни дочерних компонентов, так что для React нет никаких причин его обновлять. Это дает jQuery полную свободу управления этой частью DOM: ```js{3,4,8,12} class SomePlugin extends React.Component { @@ -39,7 +39,7 @@ class SomePlugin extends React.Component { } ``` -Note that we defined both `componentDidMount` and `componentWillUnmount` [lifecycle methods](/docs/react-component.html#the-component-lifecycle). Many jQuery plugins attach event listeners to the DOM so it's important to detach them in `componentWillUnmount`. If the plugin does not provide a method for cleanup, you will probably have to provide your own, remembering to remove any event listeners the plugin registered to prevent memory leaks. +Заметьте, что мы объявили два [метода жизненного цикла](/docs/react-component.html#the-component-lifecycle) - и `componentDidMount` и `componentWillUnmount`. Многие jQuery плагина добавляют обработчики событий для DOM, поэтмоу важно отключать их внутри `componentWillUnmount`. Если плагин не предоставляет метод для очистки, то, возможно, вам придется написать свой. Помните об удалении обработчиков события, добавленных плагином, чтобы избежать утечек памяти. ### Integrating with jQuery Chosen Plugin {#integrating-with-jquery-chosen-plugin} From f5c71b249ab01f29abb802624f9411d43495ba32 Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Sun, 17 Feb 2019 09:30:16 +0400 Subject: [PATCH 02/52] =?UTF-8?q?Choosen=20=D0=BA=D0=BE=D0=BC=D0=BF=D0=BE?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/integrating-with-other-libraries.md | 56 +++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index c9c190993..022ac9821 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -41,35 +41,35 @@ class SomePlugin extends React.Component { Заметьте, что мы объявили два [метода жизненного цикла](/docs/react-component.html#the-component-lifecycle) - и `componentDidMount` и `componentWillUnmount`. Многие jQuery плагина добавляют обработчики событий для DOM, поэтмоу важно отключать их внутри `componentWillUnmount`. Если плагин не предоставляет метод для очистки, то, возможно, вам придется написать свой. Помните об удалении обработчиков события, добавленных плагином, чтобы избежать утечек памяти. -### Integrating with jQuery Chosen Plugin {#integrating-with-jquery-chosen-plugin} +### Интеграция с jQuery плагином Chosen {#integrating-with-jquery-chosen-plugin} -For a more concrete example of these concepts, let's write a minimal wrapper for the plugin [Chosen](https://harvesthq.github.io/chosen/), which augments `` элементами. ->**Note:** +>**Примечание:** > ->Just because it's possible, doesn't mean that it's the best approach for React apps. We encourage you to use React components when you can. React components are easier to reuse in React applications, and often provide more control over their behavior and appearance. +>Да, это можно делать, но это не всегда лучший подход для React приложений. Мы советуем пользоваться React-компонентами, когда это возможно. Они являются самым простым способом переиспользовать код в React-приложения, и часто дают больший контроль над поведением и внешним видом. -First, let's look at what Chosen does to the DOM. +Для начала, давайте посмотрим, что Chosen делает с DOM. -If you call it on a ``. Then it fires jQuery events to notify us about the changes. +Когда вы вызоваете его на узле `` wrapped in a `
`: +Для начала создадим пустой компонент, с методом `render()`, который возвращает `` in an extra `
`. This is necessary because Chosen will append another DOM element right after the `` в дополнительный `
`. Это нужно потому, что Chosen добавляет новый элемент сразу за `` node in `componentDidMount`, and tear it down in `componentWillUnmount`: +Следующим шагом мы реализуем методы жизненного цикла. Нам нужно инициализировать Chosen с рефом на ` this.el = el}> ``` -This is enough to get our component to render, but we also want to be notified about the value changes. To do this, we will subscribe to the jQuery `change` event on the ``, контролируемом Chosen. -We won't pass `this.props.onChange` directly to Chosen because component's props might change over time, and that includes event handlers. Instead, we will declare a `handleChange()` method that calls `this.props.onChange`, and subscribe it to the jQuery `change` event: +Мы не станем передавать в Chosen `this.props.onChange` непосредственно, потому что пропсы компонента могут со временем изменениться (в том числе и обработчики событий). Вместо этого мы объявим метод `handleChange()`, который будет вызывать `this.props.onChange`, и подпишем его на jQuery событие `change`: ```js{5,6,10,14-16} componentDidMount() { @@ -131,11 +131,11 @@ handleChange(e) { } ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/bWgbeE?editors=0010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/bWgbeE?editors=0010) -Finally, there is one more thing left to do. In React, props can change over time. For example, the `` component can get different children if parent component's state changes. This means that at integration points it is important that we manually update the DOM in response to prop updates, since we no longer let React manage the DOM for us. +Осталась еще одна вещь, которую нужно сделать под конец. В React пропсы могут изменяться со временем. Например, `` компонент может получать разные дочерние элементы, если состояние родительского компонента изменяется. Это означает, что в точке интеграции нам нужно вручную обновлять DOM, в соответствии с обновлениями проп, так как React больше не управляет DOM для нас. -Chosen's documentation suggests that we can use jQuery `trigger()` API to notify it about changes to the original DOM element. We will let React take care of updating `this.props.children` inside ``, но нам нужно добавить метод жизненного цикла `componentDidUpdate()`, чтобы уведомлять Chosen об обновлении списка дочерних элементом: ```js{2,3} componentDidUpdate(prevProps) { @@ -145,9 +145,9 @@ componentDidUpdate(prevProps) { } ``` -This way, Chosen will know to update its DOM element when the `` были обновлены React'ом. -The complete implementation of the `Chosen` component looks like this: +Полная реализация `Chosen` компоненты выглядит так: ```js class Chosen extends React.Component { @@ -186,7 +186,7 @@ class Chosen extends React.Component { } ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/xdgKOz?editors=0010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/xdgKOz?editors=0010) ## Integrating with Other View Libraries {#integrating-with-other-view-libraries} @@ -247,7 +247,7 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/RVKbvW?editors=1010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/RVKbvW?editors=1010) You can have as many such isolated components as you like, and use `ReactDOM.render()` to render them to different DOM containers. Gradually, as you convert more of your app to React, you will be able to combine them into larger components, and move some of the `ReactDOM.render()` calls up the hierarchy. @@ -275,7 +275,7 @@ const ParagraphView = Backbone.View.extend({ }); ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/gWgOYL?editors=0010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/gWgOYL?editors=0010) It is important that we also call `ReactDOM.unmountComponentAtNode()` in the `remove` method so that React unregisters event handlers and other resources associated with the component tree when it is detached. @@ -347,7 +347,7 @@ class List extends React.Component { } ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/GmrREm?editors=0010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/GmrREm?editors=0010) ### Extracting Data from Backbone Models {#extracting-data-from-backbone-models} @@ -434,6 +434,6 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](http://codepen.io/gaearon/pen/PmWwwa?editors=0010) +[**Открыть на CodePen**](http://codepen.io/gaearon/pen/PmWwwa?editors=0010) This technique is not limited to Backbone. You can use React with any model library by subscribing to its changes in the lifecycle methods and, optionally, copying the data into the local React state. From c3e39be98c64601a5eef637cb3cfc849425f0f67 Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Sun, 17 Feb 2019 09:35:54 +0400 Subject: [PATCH 03/52] view-libraries --- content/docs/integrating-with-other-libraries.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 022ac9821..fa1b28ba5 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -188,13 +188,13 @@ class Chosen extends React.Component { [**Открыть на CodePen**](http://codepen.io/gaearon/pen/xdgKOz?editors=0010) -## Integrating with Other View Libraries {#integrating-with-other-view-libraries} +## Интеграция с другими визульными библиотеками {#integrating-with-other-view-libraries} -React can be embedded into other applications thanks to the flexibility of [`ReactDOM.render()`](/docs/react-dom.html#render). +Благодаря гибкости [`ReactDOM.render()`](/docs/react-dom.html#render) React может встраиваться с другие приложения. -Although React is commonly used at startup to load a single root React component into the DOM, `ReactDOM.render()` can also be called multiple times for independent parts of the UI which can be as small as a button, or as large as an app. +Хотя обычно React используют для загрузки в DOM одного корневого компонента, `ReactDOM.render()` может быть вызван несколько раз, для независимых частей UI. Это могут быть как отельные кнопки, так и большие приложения. -In fact, this is exactly how React is used at Facebook. This lets us write applications in React piece by piece, and combine them with our existing server-generated templates and other client-side code. +На самом деле, именно так React используется в Facebook. Это позволяет писать приложения на React по-частям и объединять их с существующими генерируемыми сервером шаблонами и другим клиентским кодом. ### Replacing String-Based Rendering with React {#replacing-string-based-rendering-with-react} From 49c87a62b4cdb50d0eeb1391db0d976f8333067d Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Sun, 17 Feb 2019 19:33:59 +0400 Subject: [PATCH 04/52] Replace string-based rendering --- .../docs/integrating-with-other-libraries.md | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index fa1b28ba5..40b89db08 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -196,24 +196,24 @@ class Chosen extends React.Component { На самом деле, именно так React используется в Facebook. Это позволяет писать приложения на React по-частям и объединять их с существующими генерируемыми сервером шаблонами и другим клиентским кодом. -### Replacing String-Based Rendering with React {#replacing-string-based-rendering-with-react} +### Замена строковых шаблонов с помощью React {#replacing-string-based-rendering-with-react} -A common pattern in older web applications is to describe chunks of the DOM as a string and insert it into the DOM like so: `$el.html(htmlString)`. These points in a codebase are perfect for introducing React. Just rewrite the string based rendering as a React component. +В старых веб-приложениях описание частей DOM c помощью строк (вроде `${el.html(htmlString)`}) является распространенным подоходом. Такие моменты прекрасно подходят, для внедрения React. Просто переписываем рендеринг на основе строк в React-компонент. -So the following jQuery implementation... +Вот такая реализация на jQuery ... ```js -$('#container').html(''); +$('#container').html(''); $('#btn').click(function() { - alert('Hello!'); + alert('Привет!'); }); ``` -...could be rewritten using a React component: +... может быть переписан на React компонентах: ```js function Button() { - return ; + return ; } ReactDOM.render( @@ -221,22 +221,22 @@ ReactDOM.render( document.getElementById('container'), function() { $('#btn').click(function() { - alert('Hello!'); + alert('Привет!'); }); } ); ``` -From here you could start moving more logic into the component and begin adopting more common React practices. For example, in components it is best not to rely on IDs because the same component can be rendered multiple times. Instead, we will use the [React event system](/docs/handling-events.html) and register the click handler directly on the React `; + return ; } function HelloButton() { function handleClick() { - alert('Hello!'); + alert('Привет!'); } return '); +$('#container').html(''); $('#btn').click(function() { alert('Привет!'); }); ``` -... может быть переписана на React компонентах: +...может быть переписана в React-компонент: ```js function Button() { @@ -227,7 +227,7 @@ ReactDOM.render( ); ``` -А дальше вы можете начать переносить логику внутрь компонента и использовать остальные React-подходы. Например, в компонентах лучше не полагаться на ID, потому что один и тот же компонент может быть отрендерен несколько раз. Вместо этого мы используем [событийную систему React](/docs/handling-events.html) и зарегестрируем обработчик непосредственно на React-элементе `; + return ; } ReactDOM.render( @@ -231,7 +231,7 @@ ReactDOM.render( ```js{2,6,9} function Button(props) { - return ; + return ; } function HelloButton() { From 3bc6630a9b50e0bcb9f0f654a86a1fff4d484dac Mon Sep 17 00:00:00 2001 From: Nick Tishkevich Date: Tue, 19 Feb 2019 03:25:24 +0400 Subject: [PATCH 37/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index ef10aaba8..cc8fd3fe3 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -69,7 +69,7 @@ function Example() { Для простоты мы будем реализовывать [неконтролируемый компонент](/docs/uncontrolled-components.html). -Сначала создадим пустой компонент, с методом `render()`, который возвращает ``, обёрнутый в `
`: ```js{4,5} class Chosen extends React.Component { From b95f122c36649e5203f10306900c5d1b2186cf00 Mon Sep 17 00:00:00 2001 From: Nick Tishkevich Date: Tue, 19 Feb 2019 03:26:42 +0400 Subject: [PATCH 38/52] Apply suggestions from code review Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index cc8fd3fe3..0390d0e71 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -85,9 +85,9 @@ class Chosen extends React.Component { } ``` -Обратите внимание, что мы обернули ``, на котором он вызывается. Но React всегда ожидает только один дочерний элемент для `
`. Так мы гарантируем, что обновления React не будут конфликтовать с дополнительным узлом, добавляемым Chosen. Если вы собираетесь изменять DOM вне React, важно убедиться, что React не должен взаимодействовать с DOM-узлами. +Обратите внимание, что мы обернули ``, на котором он вызывается. Но React всегда ожидает только один дочерний элемент для `
`. Так мы гарантируем, что обновления React не будут конфликтовать с дополнительным узлом, добавляемым Chosen. Если вы собираетесь изменять DOM вне React, важно убедиться, что React не взаимодействует с DOM-узлами. -Следующим шагом реализуем методы жизненного цикла. Нам нужно инициализировать Chosen с рефом на узле `` в `componentDidMount`, а затем убрать его в `componentWillUnmount`: ```js{2,3,7} componentDidMount() { @@ -192,7 +192,7 @@ class Chosen extends React.Component { Благодаря гибкости [`ReactDOM.render()`](/docs/react-dom.html#render) React может встраиваться в другие приложения. -Хотя обычно React используют для загрузки в DOM одного корневого компонента, `ReactDOM.render()` может быть вызван несколько раз для независимых частей UI. Это могут быть как отельные кнопки, так и большие приложения. +Хотя обычно React используют для загрузки в DOM одного корневого компонента, `ReactDOM.render()` может быть вызван несколько раз для независимых частей UI. Это могут быть как отдельные кнопки, так и большие приложения. На самом деле, именно так React используется в Facebook. Это позволяет писать приложения на React по частям и объединять их с существующими генерируемыми сервером шаблонами и другим клиентским кодом. From 51fef63d2f9b0965d1d93e1272c8be3f2f66d703 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 19 Feb 2019 04:00:31 +0400 Subject: [PATCH 39/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 0390d0e71..3c9d17ba1 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -51,7 +51,7 @@ class SomePlugin extends React.Component { Для начала, давайте посмотрим, что Chosen делает с DOM. -Когда вы вызываете его на узле ``, он читает атрибуты этого узла, скрывает его с помощью встроенных стилей и непосредственно перед ним добавляет отдельный DOM-узел с собственным визуальным представлением. Допустим, мы хотим предоставить следующий API для нашего компонента-обёртки над ``: From 25935dd175fa15e3e454045e5702d1c2ba562088 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 19 Feb 2019 04:01:30 +0400 Subject: [PATCH 40/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 3c9d17ba1..3bdfe53c6 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -47,7 +47,7 @@ class SomePlugin extends React.Component { >**Примечание:** > ->Да, это можно делать, но это не всегда лучший подход для React приложений. Мы советуем пользоваться React-компонентами, когда это возможно. Они являются самым простым способом переиспользовать код в React-приложении, и часто дают больший контроль над поведением и внешним видом. +>Да, так можно делать, но совсем не значит, что это оптимальное решение для React-приложений. Мы советуем пользоваться React-компонентами, когда это возможно. Они являются самым простым способом переиспользовать код в React-приложении, и часто дают больший контроль над поведением и внешним видом. Для начала, давайте посмотрим, что Chosen делает с DOM. From dc5a38add231fdfd2af9638f4100be3ea55cd608 Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Tue, 19 Feb 2019 15:31:05 +0400 Subject: [PATCH 41/52] Fix notice from codereview --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 3bdfe53c6..c392eae2e 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -20,7 +20,7 @@ React не знает про изменения DOM, которые сделан Мы установим [реф](/docs/refs-and-the-dom.html) на корневой DOM-элемент. Внутри `componentDidMount` мы получим ссылку и передадим её в jQuery-плагин. -Чтобы React не трогал DOM после монтирования, мы вернём пустой `
` из метода `render()`. Элемент `
` не имеет ни свойств, ни дочерних компонентов, так что для React нет никаких причин его обновлять. Это даёт jQuery полную свободу управления этой частью DOM: +Чтобы React не взаимодействовал с DOM после монтирования, вернём пустой `
` из метода `render()`. Элемент `
` не имеет ни свойств, ни дочерних компонентов, так что для React нет никаких причин его обновлять. Это даёт jQuery полную свободу управления этой частью DOM: ```js{3,4,8,12} class SomePlugin extends React.Component { From a81e2a17ff854235b4fe19f6ab4f21a063978533 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 19 Feb 2019 18:46:52 +0400 Subject: [PATCH 42/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index c392eae2e..2e514b970 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -1,6 +1,6 @@ --- id: integrating-with-other-libraries -title: Взаимодествие со сторонними библиотеками +title: Взаимодействие со сторонними библиотеками permalink: docs/integrating-with-other-libraries.html --- From af56253ea510db9992fa2af200da9f36c18bd33b Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:18:40 +0300 Subject: [PATCH 43/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 2e514b970..28b71550f 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -279,7 +279,7 @@ const ParagraphView = Backbone.View.extend({ Стоит отметить вызов `ReactDOM.unmountComponentAtNode()` в методе `remove`. Он нужен для того, чтобы React отключил обработчики событий и другие ресурсы, связанные с деревом компонентов при удалении. -Когда компонент удаляется из дерева React, очистка производится автоматически, но поскольку мы удаляем сущность из дерева вручную, то обязаны вызвать этот метод. +Когда компонент удаляется из дерева React *изнутри*, очистка производится автоматически, но поскольку мы удаляем сущность из дерева вручную, то обязаны вызвать этот метод. ## Интеграция со слоем моделей {#integrating-with-model-layers} From 7ea7cd0ceb6ea63ea2eb714d4d382a0d3f6c7eed Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:18:52 +0300 Subject: [PATCH 44/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 28b71550f..65af0a602 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -353,7 +353,7 @@ class List extends React.Component { Подход, показанный выше, требует, чтобы ваши React-компоненты знали о наличии моделей и коллекций Backbone. Если у вас в планах есть переход на другое решение для управления данными, вы, возможно, захотите максимально уменьшить связь с Backbone. -Один из подходов — вынос атрибутов моделей в простые данные, когда вы изменяете связанный код, а также хранить логику в одном месте. Следующий [компонент высшего порядка](/docs/higher-order-components.html) извлекает все атрибуты Backbone-модели в `state`, передавая данные в оборачиваемый компонент. +Один из подходов — вынос атрибутов моделей в простые данные, когда вы изменяете связанный код, а также хранение логики в одном месте. Следующий [компонент высшего порядка](/docs/higher-order-components.html) извлекает все атрибуты Backbone-модели в `state`, передавая данные в оборачиваемый компонент. При этом подходе только компоненты высшего порядка будут знать о Backbone-моделях, а большая часть компонентов в приложении не будет завязана на Backbone. From 9be8075b6fc872f3cfa93889d945b5cbf143f3a2 Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:19:51 +0300 Subject: [PATCH 45/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 65af0a602..ff985eb14 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -357,7 +357,7 @@ class List extends React.Component { При этом подходе только компоненты высшего порядка будут знать о Backbone-моделях, а большая часть компонентов в приложении не будет завязана на Backbone. -В примере ниже, мы сделаем копию атрибутов модели для формирования начального состояния. Мы подпишемся на событие `change` (и отпишется от него при удалении), и когда оно будет возникать мы обновим состояние текущими атрибутами. Наконец, мы убедимся, что если пропадает сама `model`, мы не забываем отписаться от старой модели и подписаться на новую. +В примере ниже, мы сделаем копию атрибутов модели для формирования начального состояния. Мы подпишемся на событие `change` (и отпишемся от него при удалении), и когда оно будет возникать, мы обновим состояние текущими атрибутами. Наконец, мы убедимся, что если изменяется сам проп `model`, мы не забываем отписаться от старой модели и подписаться на новую. Обратите внимание, пример ниже не является полным в отношении работы с Backbone. Но он должен дать вам понимание общего подхода: From 8a41f04f6cc567abbb07872f47688e1832cf0b6c Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:20:11 +0300 Subject: [PATCH 46/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index ff985eb14..e6288719f 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -436,4 +436,4 @@ ReactDOM.render( [**Посмотреть на CodePen**](http://codepen.io/gaearon/pen/PmWwwa?editors=0010) -Этот подход не ограничивается Backbone. Вы можете использовать React с любой библиотекой для работы с данными, просто подписываясь на методы жизненно цикла и, при необходимости, копируя данные во внутреннее состояние React. +Этот подход не ограничивается Backbone. Вы можете использовать React с любой библиотекой для работы с данными, просто подписываясь на методы жизненного цикла и, при необходимости, копируя данные во внутреннее состояние React. From 1586594fa686e38b7b34bbae4f4043ac66d944a9 Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:20:20 +0300 Subject: [PATCH 47/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index e6288719f..7bf1e0051 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -51,7 +51,7 @@ class SomePlugin extends React.Component { Для начала, давайте посмотрим, что Chosen делает с DOM. -Когда вы вызываете его на DOM-узле ``, он читает атрибуты этого узла, скрывает его с помощью встроенных стилей и непосредственно перед ним добавляет отдельный DOM-узел с собственным визуальным представлением. Затем он запускает события jQuery, чтобы уведомлять нас об изменениях. Допустим, мы хотим предоставить следующий API для нашего компонента-обёртки над ``: From 1db5c91b17f4342e96ad13f5ebf42d32c7ec7249 Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:20:31 +0300 Subject: [PATCH 48/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 7bf1e0051..4234b6451 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -47,7 +47,7 @@ class SomePlugin extends React.Component { >**Примечание:** > ->Да, так можно делать, но совсем не значит, что это оптимальное решение для React-приложений. Мы советуем пользоваться React-компонентами, когда это возможно. Они являются самым простым способом переиспользовать код в React-приложении, и часто дают больший контроль над поведением и внешним видом. +> То, что следующий способ работает, совсем не значит, что это оптимальное решение для React-приложений. Мы советуем пользоваться React-компонентами, когда это возможно. Они являются самым простым способом переиспользовать код в React-приложении, и часто дают больший контроль над своим поведением и внешним видом. Для начала, давайте посмотрим, что Chosen делает с DOM. From 187b6682ccf1d3c838a9c8a351c81ff42a8def2c Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:20:41 +0300 Subject: [PATCH 49/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 4234b6451..17bfdf08a 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -39,7 +39,7 @@ class SomePlugin extends React.Component { } ``` -Заметьте, что мы объявили два [метода жизненного цикла](/docs/react-component.html#the-component-lifecycle) — как `componentDidMount`, так и `componentWillUnmount`. Многие jQuery-плагины добавляют обработчики событий DOM, поэтому важно отключать их внутри `componentWillUnmount`. Если плагин не предоставляет метод для очистки, то, возможно, вам придётся написать свой. Помните об удалении обработчиков событий, добавленных плагином, чтобы избежать утечек памяти. +Заметьте, что мы объявили два [метода жизненного цикла](/docs/react-component.html#the-component-lifecycle) — как `componentDidMount`, так и `componentWillUnmount`. Многие jQuery-плагины добавляют обработчики событий DOM, поэтому важно удалять их внутри `componentWillUnmount`. Если плагин не предоставляет метод для очистки, то, возможно, вам придётся написать свой. Помните об удалении обработчиков событий, добавленных плагином, чтобы избежать утечек памяти. ### Интеграция с jQuery-плагином Chosen {#integrating-with-jquery-chosen-plugin} From 51893902d735d09a74992418bc5fb7f9bf503ff6 Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:20:51 +0300 Subject: [PATCH 50/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 17bfdf08a..14c03a746 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -16,7 +16,7 @@ React не знает про изменения DOM, которые сделан ### Как решить проблему {#how-to-approach-the-problem} -Для демонстрации давайте набросаем обертку вокруг обобщенного jQuery плагина. +Для демонстрации давайте набросаем обертку вокруг обобщенного jQuery-плагина. Мы установим [реф](/docs/refs-and-the-dom.html) на корневой DOM-элемент. Внутри `componentDidMount` мы получим ссылку и передадим её в jQuery-плагин. From 12f6391c4cf19e6a9273c4b336a048681f9402b5 Mon Sep 17 00:00:00 2001 From: ANOTHER GUY Date: Fri, 22 Feb 2019 19:21:19 +0300 Subject: [PATCH 51/52] Update content/docs/integrating-with-other-libraries.md Co-Authored-By: vvscode --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index 14c03a746..beb573e9b 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -18,7 +18,7 @@ React не знает про изменения DOM, которые сделан Для демонстрации давайте набросаем обертку вокруг обобщенного jQuery-плагина. -Мы установим [реф](/docs/refs-and-the-dom.html) на корневой DOM-элемент. Внутри `componentDidMount` мы получим ссылку и передадим её в jQuery-плагин. +Мы установим [реф](/docs/refs-and-the-dom.html) на корневой DOM-элемент. Внутри `componentDidMount` мы получим ссылку на этот реф и передадим её в jQuery-плагин. Чтобы React не взаимодействовал с DOM после монтирования, вернём пустой `
` из метода `render()`. Элемент `
` не имеет ни свойств, ни дочерних компонентов, так что для React нет никаких причин его обновлять. Это даёт jQuery полную свободу управления этой частью DOM: From a12b00032f2f41db270b1b94cf5ced3b74b586b5 Mon Sep 17 00:00:00 2001 From: "Vasiliy Vanchuk (@vvscode)" Date: Fri, 22 Feb 2019 19:28:09 +0300 Subject: [PATCH 52/52] Changes from code review --- content/docs/integrating-with-other-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md index beb573e9b..87b136afb 100644 --- a/content/docs/integrating-with-other-libraries.md +++ b/content/docs/integrating-with-other-libraries.md @@ -353,7 +353,7 @@ class List extends React.Component { Подход, показанный выше, требует, чтобы ваши React-компоненты знали о наличии моделей и коллекций Backbone. Если у вас в планах есть переход на другое решение для управления данными, вы, возможно, захотите максимально уменьшить связь с Backbone. -Один из подходов — вынос атрибутов моделей в простые данные, когда вы изменяете связанный код, а также хранение логики в одном месте. Следующий [компонент высшего порядка](/docs/higher-order-components.html) извлекает все атрибуты Backbone-модели в `state`, передавая данные в оборачиваемый компонент. +Один из подходов — когда при каждом изменении модели, вы извлекаете её атрибуты в виде простых данных и храните всю логику в одном месте. Следующий [компонент высшего порядка](/docs/higher-order-components.html) извлекает все атрибуты Backbone-модели в `state`, передавая данные в оборачиваемый компонент. При этом подходе только компоненты высшего порядка будут знать о Backbone-моделях, а большая часть компонентов в приложении не будет завязана на Backbone.