`.
->Note
+>Примечание
>
->The second `ref` argument only exists when you define a component with `React.forwardRef` call. Regular function or class components don't receive the `ref` argument, and ref is not available in props either.
+>Второй аргумент `ref` существует только в том случае, если вы создаёте компонент через функцию `React.forwardRef`. Обычные функциональные или классовые компоненты не получают `ref` в качестве аргумента или пропа.
>
->Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
+>Перенаправить реф можно не только в DOM-компонент, но и в экземпляр классового компонента.
-## Note for component library maintainers {#note-for-component-library-maintainers}
+## Примечание для разработчиков библиотек компонентов {#note-for-component-library-maintainers}
-**When you start using `forwardRef` in a component library, you should treat it as a breaking change and release a new major version of your library.** This is because your library likely has an observably different behavior (such as what refs get assigned to, and what types are exported), and this can break apps and other libraries that depend on the old behavior.
+**Если вы впервые использовали `forwardRef` в компоненте библиотеки, то следует сделать новую версию мажорной и указать на обратную несовместимость изменений.** Причина этого в том, что, скорее всего, компонент станет вести себя заметно иначе (например, изменится тип экспортируемых данных и элемент, к которому привязан реф), в результате чего приложения и другие библиотеки, полагающиеся на старое поведение, перестанут работать.
-Conditionally applying `React.forwardRef` when it exists is also not recommended for the same reasons: it changes how your library behaves and can break your users' apps when they upgrade React itself.
+По этой же причине мы рекомендуем не вызывать `React.forwardRef` условно (то есть сперва проверяя, что эта функция определена). Это изменит поведение вашей библиотеки и приложения ваших пользователей могут перестать работать при обновлении самого React.
+## Перенаправление рефов в компонентах высшего порядка {#forwarding-refs-in-higher-order-components}
-## Forwarding refs in higher-order components {#forwarding-refs-in-higher-order-components}
-
-This technique can also be particularly useful with [higher-order components](/docs/higher-order-components.html) (also known as HOCs). Let's start with an example HOC that logs component props to the console:
+Особенно полезным перенаправление может оказаться в [компонентах высшего порядка](/docs/higher-order-components.html) (также известных как HOC). Начнём с примера, в котором HOC выводит пропсы компонента в консоль:
`embed:forwarding-refs/log-props-before.js`
-The "logProps" HOC passes all `props` through to the component it wraps, so the rendered output will be the same. For example, we can use this HOC to log all props that get passed to our "fancy button" component:
+Компонент высшего порядка `logProps` передаёт все пропсы в компонент, который он оборачивает, так что рендерить они будут одно и то же. С его помощью мы будем выводить в консоль все пропсы, переданные в наш компонент с кнопкой:
`embed:forwarding-refs/fancy-button.js`
-There is one caveat to the above example: refs will not get passed through. That's because `ref` is not a prop. Like `key`, it's handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.
+Обратите внимание, что в этом примере не будут передаваться рефы. Так происходит, потому что `ref` это не проп. Подобно `key`, React обрабатывает `ref` особым образом. Если вы укажите реф для HOC, он привяжется к ближайшему к корню контейнера, а не к переданному в HOC компоненту.
-This means that refs intended for our `FancyButton` component will actually be attached to the `LogProps` component:
+Следовательно, рефы, предназначенные для компонента `FancyButton`, окажутся привязанными к компоненту `LogProps`:
`embed:forwarding-refs/fancy-button-ref.js`
-Fortunately, we can explicitly forward refs to the inner `FancyButton` component using the `React.forwardRef` API. `React.forwardRef` accepts a render function that receives `props` and `ref` parameters and returns a React node. For example:
+К счастью, мы можем явно перенаправить рефы на компонент `FancyButton` внутри HOC при помощи API `React.forwardRef`. В `React.forwardRef` передаётся функция рендеринга, которая принимает аргументы `props` и `ref`, а возвращает узел React. Например:
`embed:forwarding-refs/log-props-after.js`
-## Displaying a custom name in DevTools {#displaying-a-custom-name-in-devtools}
+## Изменение названия в инструментах разработки {#displaying-a-custom-name-in-devtools}
-`React.forwardRef` accepts a render function. React DevTools uses this function to determine what to display for the ref forwarding component.
+В `React.forwardRef` передаётся функция рендеринга. Эта функция определяет, как будет называться компонент в инструментах разработки.
-For example, the following component will appear as "*ForwardRef*" in the DevTools:
+Например, вот этот компонент будет называться «*ForwardRef*»:
`embed:forwarding-refs/wrapped-component.js`
-If you name the render function, DevTools will also include its name (e.g. "*ForwardRef(myFunction)*"):
+Если присвоить имя функции рендеринга, то оно появится в названии компонента в инструментах разработки (например, «*ForwardRef(myFunction)*»):
`embed:forwarding-refs/wrapped-component-with-function-name.js`
-You can even set the function's `displayName` property to include the component you're wrapping:
+Можно даже назначить функции свойство `displayName` и указать в нём, какой именно компонент обёрнут в HOC:
`embed:forwarding-refs/customized-display-name.js`
diff --git a/content/docs/fragments.md b/content/docs/fragments.md
index 04de0463b..7c7b20955 100644
--- a/content/docs/fragments.md
+++ b/content/docs/fragments.md
@@ -1,10 +1,10 @@
---
id: fragments
-title: Fragments
+title: Фрагменты
permalink: docs/fragments.html
---
-A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
+Возврат нескольких элементов из компонента является распространённой практикой в React. Фрагменты позволяют формировать список дочерних элементов, не создавая лишних узлов в DOM.
```js
render() {
@@ -18,11 +18,11 @@ render() {
}
```
-There is also a new [short syntax](#short-syntax) for declaring them, but it isn't supported by all popular tools yet.
+Также существует [сокращённая запись](#short-syntax), однако не все популярные инструменты поддерживают её.
-## Motivation {#motivation}
+## Мотивация {#motivation}
-A common pattern is for a component to return a list of children. Take this example React snippet:
+Возврат списка дочерних элементов из компонента – распространённая практика. Рассмотрим пример на React:
```jsx
class Table extends React.Component {
@@ -38,7 +38,7 @@ class Table extends React.Component {
}
```
-` ` would need to return multiple `` elements in order for the rendered HTML to be valid. If a parent div was used inside the `render()` of ` `, then the resulting HTML will be invalid.
+` ` должен вернуть несколько элементов ` `, чтобы HTML получился валидным. Если использовать div как родительский элемент внутри метода `render()` компонента ` `, то HTML окажется невалидным.
```jsx
class Columns extends React.Component {
@@ -53,7 +53,7 @@ class Columns extends React.Component {
}
```
-results in a `` output of:
+результатом вывода `` будет:
```jsx
@@ -66,9 +66,9 @@ results in a `` output of:
```
-Fragments solve this problem.
+Фрагменты решают эту проблему.
-## Usage {#usage}
+## Использование {#usage}
```jsx{4,7}
class Columns extends React.Component {
@@ -83,7 +83,7 @@ class Columns extends React.Component {
}
```
-which results in a correct `` output of:
+результатом будет правильный вывод ``:
```jsx
@@ -94,9 +94,9 @@ which results in a correct `` output of:
```
-### Short Syntax {#short-syntax}
+### Сокращённая запись {#short-syntax}
-There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:
+Существует сокращённая запись объявления фрагментов. Она выглядит как пустые теги:
```jsx{4,7}
class Columns extends React.Component {
@@ -111,20 +111,20 @@ class Columns extends React.Component {
}
```
-You can use `<>>` the same way you'd use any other element except that it doesn't support keys or attributes.
+Можно использовать `<>>` так же, как используется любой другой элемент. Однако такая запись не поддерживает ключи или атрибуты.
-Note that **[many tools don't support it yet](/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax)** so you might want to explicitly write `` until the tooling catches up.
+Обратите внимание, что **[большинство инструментов ещё не поддерживают сокращённую запись](/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax)**, поэтому можно явно указывать ``, пока не появится поддержка.
-### Keyed Fragments {#keyed-fragments}
+### Фрагменты с ключами {#keyed-fragments}
-Fragments declared with the explicit `` syntax may have keys. A use case for this is mapping a collection to an array of fragments -- for example, to create a description list:
+Фрагменты, объявленные с помощью ``, могут иметь ключи. Например, их можно использовать при создании списка определений, преобразовав коллекцию в массив фрагментов.
```jsx
function Glossary(props) {
return (
{props.items.map(item => (
- // Without the `key`, React will fire a key warning
+ // Без указания атрибута `key`, React выдаст предупреждение об его отсутствии
{item.term}
{item.description}
@@ -135,8 +135,8 @@ function Glossary(props) {
}
```
-`key` is the only attribute that can be passed to `Fragment`. In the future, we may add support for additional attributes, such as event handlers.
+`key` – это единственный атрибут, допустимый у `Fragment`. В будущем мы планируем добавить поддержку дополнительных атрибутов, например, обработчиков событий.
-### Live Demo {#live-demo}
+### Живой пример {#live-demo}
-You can try out the new JSX fragment syntax with this [CodePen](https://codepen.io/reactjs/pen/VrEbjE?editors=1000).
+Новый синтаксис JSX фрагментов можно попробовать на [CodePen](https://codepen.io/reactjs/pen/VrEbjE?editors=1000).
diff --git a/content/docs/getting-started.md b/content/docs/getting-started.md
index 5625bb3cd..6f7c55a32 100644
--- a/content/docs/getting-started.md
+++ b/content/docs/getting-started.md
@@ -1,6 +1,6 @@
---
id: getting-started
-title: Getting Started
+title: Начало работы
permalink: docs/getting-started.html
next: add-react-to-a-website.html
redirect_from:
@@ -18,109 +18,109 @@ redirect_from:
- "docs/environments.html"
---
-This page is an overview of the React documentation and related resources.
+На этой странице мы сделаем небольшой обзор документации и других ресурсов, которые могут пригодиться при первом использовании React.
-**React** is a JavaScript library for building user interfaces. Learn what React is all about on [our homepage](/) or [in the tutorial](/tutorial/tutorial.html).
+**React** — это JavaScript-библиотека для разработки пользовательского интерфейса. Чтобы составить первое впечатление о React, зайдите на [главную страницу](/) или во [введение](/tutorial/tutorial.html).
---
-- [Try React](#try-react)
-- [Learn React](#learn-react)
-- [Staying Informed](#staying-informed)
-- [Versioned Documentation](#versioned-documentation)
-- [Something Missing?](#something-missing)
+- [Пробуем React](#try-react)
+- [Изучаем React](#learn-react)
+- [Информация о релизах](#staying-informed)
+- [Документация на старые версии React](#versioned-documentation)
+- [Обратная связь](#something-missing)
-## Try React {#try-react}
+## Пробуем React {#try-react}
-React has been designed from the start for gradual adoption, and **you can use as little or as much React as you need.** Whether you want to get a taste of React, add some interactivity to a simple HTML page, or start a complex React-powered app, the links in this section will help you get started.
+React изначально был спроектирован так, чтобы его можно было внедрять постепенно. Другими словами, **вы можете начать с малого и использовать только тот функционал React, который необходим вам в данный момент.** Информация в этом разделе будет полезна в любой ситуации: при первом знакомстве с React, при создании простой динамической HTML-страницы и даже при проектировании сложного React-приложения.
-### Online Playgrounds {#online-playgrounds}
+### Онлайн-песочницы {#online-playgrounds}
-If you're interested in playing around with React, you can use an online code playground. Try a Hello World template on [CodePen](codepen://hello-world) or [CodeSandbox](https://codesandbox.io/s/new).
+Если вы просто хотите немного поиграть с React, попробуйте онлайн-песочницу. Например, вот простейший шаблон на [CodePen](codepen://hello-world) или [CodeSandbox](https://codesandbox.io/s/new).
-If you prefer to use your own text editor, you can also [download this HTML file](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html), edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so we'd only recommend using this for simple demos.
+Если вы предпочитаете работать в своем редакторе, [скачайте тестовый HTML-файл](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html), добавьте в него код и запустите на своем компьютере. При открытии тестового файла браузер преобразует JSX в обычный код на JavaScript. Такое преобразование достаточно медленно, поэтому мы рекомендуем использовать этот файл только для простых демонстрационных примеров.
-### Add React to a Website {#add-react-to-a-website}
+### Добавляем React на сайт {#add-react-to-a-website}
-You can [add React to an HTML page in one minute](/docs/add-react-to-a-website.html). You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.
+Вы можете [добавить React на свой сайт буквально за одну минуту](/docs/add-react-to-a-website.html). После этого можно разместить на сайте несколько динамических виджетов и постепенно наращивать использование React в своём проекте.
-### Create a New React App {#create-a-new-react-app}
+### Создаём React-приложение {#create-a-new-react-app}
-When starting a React project, [a simple HTML page with script tags](/docs/add-react-to-a-website.html) might still be the best option. It only takes a minute to set up!
+Когда вы начинаете проект на React, [то простая HTML-страница со script-тегами](/docs/add-react-to-a-website.html) может быть лучшим вариантом. Её можно сделать за минуту.
-As your application grows, you might want to consider a more integrated setup. There are [several JavaScript toolchains](/docs/create-a-new-react-app.html) we recommend for larger applications. Each of them can work with little to no configuration and lets you take full advantage of the rich React ecosystem.
+Однако для разработки более развесистого приложения вам, скорее всего, придётся рассмотреть другие варианты настройки рабочего окружения, объединяющие в себе различные технологии. Вот [несколько наборов JavaScript-инструментов](/docs/create-a-new-react-app.html), которые мы рекомендуем для создания сложных приложений. Каждый из этих инструментов может работать практически без настройки и позволит раскрыть все возможности экосистемы React.
-## Learn React {#learn-react}
+## Изучаем React {#learn-react}
-People come to React from different backgrounds and with different learning styles. Whether you prefer a more theoretical or a practical approach, we hope you'll find this section helpful.
+Люди приходят к React с разным опытом и стилем обучения. Некоторые предпочитают учиться на ходу, а кому-то нравится сначала овладеть теорией. В любом случае мы надеемся, что этот раздел будет для вас полезен.
-* If you prefer to **learn by doing**, start with our [practical tutorial](/tutorial/tutorial.html).
-* If you prefer to **learn concepts step by step**, start with our [guide to main concepts](/docs/hello-world.html).
+* Если вам больше нравится **учиться на ходу**, начните с [введения](/tutorial/tutorial.html).
+* Если вы хотите **сначала овладеть теорией**, то начните с [пошагового описания React](/docs/hello-world.html).
-Like any unfamiliar technology, React does have a learning curve. With practice and some patience, you *will* get the hang of it.
+React сначала может показаться сложным, но приложив усилие, вы *обязательно* его освоите. Терпение и труд все перетрут!
-### First Examples {#first-examples}
+### Простые примеры {#first-examples}
-The [React homepage](/) contains a few small React examples with a live editor. Even if you don't know anything about React yet, try changing their code and see how it affects the result.
+На [главной странице](/) есть несколько простых примеров использования React. Их можно отредактировать и запустить прямо на нашем сайте. Даже если вы пока ничего не знаете о React, попробуйте что-нибудь поменять в коде и посмотрите на результат.
-### React for Beginners {#react-for-beginners}
+### React для новичков {#react-for-beginners}
-If you feel that the React documentation goes at a faster pace than you're comfortable with, check out [this overview of React by Tania Rascia](https://www.taniarascia.com/getting-started-with-react/). It introduces the most important React concepts in a detailed, beginner-friendly way. Once you're done, give the documentation another try!
+Если документация кажется вам сложной и усваивается не так быстро, как хотелось, прочтите [блог Тани Раша (Tania Rascia)](https://www.taniarascia.com/getting-started-with-react/). Таня написала о том, как начала работать с React и доходчиво рассказала об его основных принципах. Попробуйте почитать этот пост, а потом вернуться к документации.
-### React for Designers {#react-for-designers}
+### React для дизайнеров {#react-for-designers}
-If you're coming from a design background, [these resources](http://reactfordesigners.com/) are a great place to get started.
+Если вы в первую очередь занимаетесь дизайном, вам могут пригодиться ресурсы, собранные [на этом сайте](https://reactfordesigners.com/).
-### JavaScript Resources {#javascript-resources}
+### Ресурсы по JavaScript {#javascript-resources}
-The React documentation assumes some familiarity with programming in the JavaScript language. You don't have to be an expert, but it's harder to learn both React and JavaScript at the same time.
+Изучение React предполагает наличие некоторых знаний о программировании на языке JavaScript. Глубоких знаний не потребуется, но учить React и JavaScript одновременно может быть тяжело.
-We recommend going through [this JavaScript overview](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) to check your knowledge level. It will take you between 30 minutes and an hour but you will feel more confident learning React.
+Чтобы освежить ваши знания, мы рекомендуем просмотреть [обзор языка JavaScript на сайте mozilla.org](https://developer.mozilla.org/ru/docs/Web/JavaScript/A_re-introduction_to_JavaScript). Для этого потребуется от 30 минут до часа. Надеемся, что теперь вы будете чувствовать себя более комфортно, изучая React.
->Tip
+>Совет
>
->Whenever you get confused by something in JavaScript, [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and [javascript.info](http://javascript.info/) are great websites to check. There are also [community support forums](/community/support.html) where you can ask for help.
+>Если всё-таки у вас есть пробелы в знаниях, то сайты [MDN](https://developer.mozilla.org/ru/docs/Web/JavaScript) и [javascript.info](https://javascript.info/) будут отличными источниками информации о JavaScript. Также всегда можно задать вопрос или попросить помощи на [форумах нашего сообщества](/community/support.html).
-### Practical Tutorial {#practical-tutorial}
+### Введение {#practical-tutorial}
-If you prefer to **learn by doing,** check out our [practical tutorial](/tutorial/tutorial.html). In this tutorial, we build a tic-tac-toe game in React. You might be tempted to skip it because you're not building games -- but give it a chance. The techniques you'll learn in the tutorial are fundamental to building *any* React apps, and mastering it will give you a much deeper understanding.
+Если вы предпочитаете **изучать технологии на практике**, воспользуйтесь [введением](/tutorial/tutorial.html). В нём описан процесс разработки игры в крестики-нолики. Даже если вы не планируете программировать игры, всё равно уделите внимание этому разделу документации. Приёмы, которые вы освоите — фундамент для разработки *любых* приложений на React. [Введение](/tutorial/tutorial.html) даст вам более глубокое понимание React.
-### Step-by-Step Guide {#step-by-step-guide}
+### Пошаговое описание React {#step-by-step-guide}
-If you prefer to **learn concepts step by step,** our [guide to main concepts](/docs/hello-world.html) is the best place to start. Every next chapter in it builds on the knowledge introduced in the previous chapters so you won't miss anything as you go along.
+Если вам больше нравится **познавать предмет шаг за шагом**, то лучше начать с [пошагового описания React](/docs/hello-world.html). Каждая последующая глава описания опирается на знания из предыдущей, поэтому вы ничего не упустите в процессе изучения материала.
-### Thinking in React {#thinking-in-react}
+### Философия React {#thinking-in-react}
-Many React users credit reading [Thinking in React](/docs/thinking-in-react.html) as the moment React finally "clicked" for them. It's probably the oldest React walkthrough but it's still just as relevant.
+Многие вспоминают, как чтение [Философии React](/docs/thinking-in-react.html) поставило всё на свои места. Пускай это и самое древнее руководство по React, но оно всё так же актуально.
-### Recommended Courses {#recommended-courses}
+### Рекомендуемые курсы {#recommended-courses}
-Sometimes people find third-party books and video courses more helpful than the official documentation. We maintain [a list of commonly recommended resources](/community/courses.html), some of which are free.
+Некоторым больше нравится учиться по книгам или видеокурсам от сторонних авторов, а не по официальной документации. Для них мы разместили [список рекомендуемых ресурсов](/community/courses.html). Часть этих ресурсов бесплатны.
-### Advanced Concepts {#advanced-concepts}
+### Углублённое изучение React {#advanced-concepts}
-Once you're comfortable with the [main concepts](#main-concepts) and played with React a little bit, you might be interested in more advanced topics. This section will introduce you to the powerful, but less commonly used React features like [context](/docs/context.html) and [refs](/docs/refs-and-the-dom.html).
+После того, как вы изучите [основные принципы React](#main-concepts) и немного поиграетесь с ним, можно углубиться в более продвинутые темы документации. В этих главах описан полезный, но не так часто используемый функционал React. Например, [контекст](/docs/context.html) и [рефы](/docs/refs-and-the-dom.html).
-### API Reference {#api-reference}
+### Справочник API {#api-reference}
-This documentation section is useful when you want to learn more details about a particular React API. For example, [`React.Component` API reference](/docs/react-component.html) can provide you with details on how `setState()` works, and what different lifecycle methods are useful for.
+Этот раздел документации описывает нюансы использования React API. Например, в главе [`React.Component` API](/docs/react-component.html) рассказывается о работе функции `setState()` и различных методах управления жизненным циклом компонентов.
-### Glossary and FAQ {#glossary-and-faq}
+### Глоссарий и FAQ {#glossary-and-faq}
-The [glossary](/docs/glossary.html) contains an overview of the most common terms you'll see in the React documentation. There is also a FAQ section dedicated to short questions and answers about common topics, including [making AJAX requests](/docs/faq-ajax.html), [component state](/docs/faq-state.html), and [file structure](/docs/faq-structure.html).
+[Глоссарий](/docs/glossary.html) содержит перечень наиболее употребляемых терминов, которые встречаются в документации. Также есть раздел FAQ. В нём короткие вопросы и ответы на самые животрепещущие темы, такие как [использование AJAX](/docs/faq-ajax.html), [состояние компонентов](/docs/faq-state.html) или [структура проекта](/docs/faq-structure.html).
-## Staying Informed {#staying-informed}
+## Информация о релизах {#staying-informed}
-The [React blog](/blog/) is the official source for the updates from the React team. Anything important, including release notes or deprecation notices, will be posted there first.
+В [официальном блоге](/blog/) мы сообщаем о новых релизах React. Все самые важные новости, включая списки изменений и нерекомендуемых к использованию функций, публикуются в первую очередь здесь.
-You can also follow the [@reactjs account](https://twitter.com/reactjs) on Twitter, but you won't miss anything essential if you only read the blog.
+Также вы можете подписаться на наш аккаунт [@reactjs](https://twitter.com/reactjs) в Twitter. Однако вы не пропустите ничего важного, если будете следить только за блогом.
-Not every React release deserves its own blog post, but you can find a detailed changelog for every release [in the `CHANGELOG.md` file in the React repository](https://github.com/facebook/react/blob/master/CHANGELOG.md), as well as on the [Releases](https://github.com/facebook/react) page.
+В блоге мы пишем не о всех релизах React, но всегда есть возможность посмотреть полный список изменений [в файле `CHANGELOG.md` в репозитории React](https://github.com/facebook/react/blob/master/CHANGELOG.md), а также на странице [Релизы](https://github.com/facebook/react).
-## Versioned Documentation {#versioned-documentation}
+## Документация на старые версии React {#versioned-documentation}
-This documentation always reflects the latest stable version of React. Since React 16, you can find older versions of the documentation [on a separate page](/versions). Note that documentation for past versions is snapshotted at the time of the release, and isn't being continuously updated.
+Документация на сайте всегда соответствует последнему стабильному релизу. Начиная с 16 версии React, мы публикуем старые версии документации [на отдельной странице](/versions). Учтите, что копии документации создаются в момент выхода релиза и больше не обновляются.
-## Something Missing? {#something-missing}
+## Обратная связь {#something-missing}
-If something is missing in the documentation or if you found some part confusing, please [file an issue for the documentation repository](https://github.com/reactjs/reactjs.org/issues/new) with your suggestions for improvement, or tweet at the [@reactjs account](https://twitter.com/reactjs). We love hearing from you!
+Если вы обнаружите в документации какие-нибудь неточности, ошибки или любые другие непонятки, пожалуйста, [создайте ишью в репозитории документации](https://github.com/reactjs/reactjs.org/issues/new) с указанием способа решения проблемы или просто [чирикните нам в Twitter @reactjs](https://twitter.com/reactjs). Мы всегда рады слышать вас!
diff --git a/content/docs/handling-events.md b/content/docs/handling-events.md
index a8d3a1f51..4abac4892 100644
--- a/content/docs/handling-events.md
+++ b/content/docs/handling-events.md
@@ -1,6 +1,6 @@
---
id: handling-events
-title: Handling Events
+title: Обработка событий
permalink: docs/handling-events.html
prev: state-and-lifecycle.html
next: conditional-rendering.html
@@ -8,57 +8,57 @@ redirect_from:
- "docs/events-ko-KR.html"
---
-Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
+Обработка событий в React-элементах очень похожа на обработку событий в DOM-элементах. Но есть несколько синтаксических отличий:
-* React events are named using camelCase, rather than lowercase.
-* With JSX you pass a function as the event handler, rather than a string.
+* События в React именуются в стиле camelCase вместо нижнего регистра.
+* С JSX вы передаёте функцию как обработчик события вместо строки.
-For example, the HTML:
+Например, в HTML:
```html
- Activate Lasers
+ Активировать лазеры
```
-is slightly different in React:
+В React немного иначе:
```js{1}
- Activate Lasers
+ Активировать лазеры
```
-Another difference is that you cannot return `false` to prevent default behavior in React. You must call `preventDefault` explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:
+Еще одно отличие — в React нельзя предотвратить обработчик события по умолчанию, вернув `false`. Нужно явно вызвать `preventDefault`. Например, в обычном HTML, чтобы отменить выполнение встроенного обработчика события у ссылки, которое открывает новую страницу, можно написать:
```html
-
- Click me
+
+ Кликни меня
```
-In React, this could instead be:
+В React это будет выглядеть так:
```js{2-5,8}
function ActionLink() {
function handleClick(e) {
e.preventDefault();
- console.log('The link was clicked.');
+ console.log('По ссылке кликнули.');
}
return (
- Click me
+ Кликни меня
);
}
```
-Here, `e` is a synthetic event. React defines these synthetic events according to the [W3C spec](https://www.w3.org/TR/DOM-Level-3-Events/), so you don't need to worry about cross-browser compatibility. See the [`SyntheticEvent`](/docs/events.html) reference guide to learn more.
+В приведённом выше коде `e` — это синтетическое событие. React определяет синтетические события в соответствии со [спецификацией W3C](https://www.w3.org/TR/DOM-Level-3-Events/), поэтому не волнуйтесь о кроссбраузерности. Посмотрите [руководство о `SyntheticEvent`](/docs/events.html), чтобы узнать о них больше.
-When using React you should generally not need to call `addEventListener` to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.
+При использовании React обычно не нужно вызывать `addEventListener`, чтобы добавить обработчики в DOM-элемент после его создания. Вместо этого добавьте обработчик сразу после того, как элемент отрендерился.
-When you define a component using an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), a common pattern is for an event handler to be a method on the class. For example, this `Toggle` component renders a button that lets the user toggle between "ON" and "OFF" states:
+В компоненте, определённом с помощью [ES6-класса](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes), в качестве обработчика события обычно выступает один из методов класса. Например, этот компонент `Toggle` рендерит кнопку, которая позволяет пользователю переключать состояния между «Включено» и «Выключено»:
```js{6,7,10-14,18}
class Toggle extends React.Component {
@@ -66,7 +66,7 @@ class Toggle extends React.Component {
super(props);
this.state = {isToggleOn: true};
- // This binding is necessary to make `this` work in the callback
+ // Эта привязка обязательна для работы `this` в колбэке.
this.handleClick = this.handleClick.bind(this);
}
@@ -79,7 +79,7 @@ class Toggle extends React.Component {
render() {
return (
- {this.state.isToggleOn ? 'ON' : 'OFF'}
+ {this.state.isToggleOn ? 'Включено' : 'Выключено'}
);
}
@@ -91,64 +91,64 @@ ReactDOM.render(
);
```
-[**Try it on CodePen**](http://codepen.io/gaearon/pen/xEmzGg?editors=0010)
+[**Посмотреть на CodePen**](https://codepen.io/gaearon/pen/xEmzGg?editors=0010)
-You have to be careful about the meaning of `this` in JSX callbacks. In JavaScript, class methods are not [bound](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) by default. If you forget to bind `this.handleClick` and pass it to `onClick`, `this` will be `undefined` when the function is actually called.
+При обращении к `this` в JSX-колбэках необходимо учитывать, что методы класса в JavaScript по умолчанию не [привязаны](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) к контексту. Если вы забудете привязать метод `this.handleClick` и передать его в `onClick`, значение `this` будет `undefined` в момент вызова функции.
-This is not React-specific behavior; it is a part of [how functions work in JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Generally, if you refer to a method without `()` after it, such as `onClick={this.handleClick}`, you should bind that method.
+Дело не в работе React, это часть того, [как работают функции в JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Обычно, если ссылаться на метод без `()` после него, например, `onClick={this.handleClick}`, этот метод нужно привязать.
-If calling `bind` annoys you, there are two ways you can get around this. If you are using the experimental [public class fields syntax](https://babeljs.io/docs/plugins/transform-class-properties/), you can use class fields to correctly bind callbacks:
+Если вам не по душе `bind`, существует два других способа. Если вы пользуетесь экспериментальным [синтаксисом общедоступных полей классов](https://babeljs.io/docs/plugins/transform-class-properties/), вы можете использовать его, чтобы правильно привязать колбэки:
```js{2-6}
class LoggingButton extends React.Component {
- // This syntax ensures `this` is bound within handleClick.
- // Warning: this is *experimental* syntax.
+ // Такой синтаксис гарантирует, что `this` привязан к handleClick.
+ // Предупреждение: это экспериментальный синтаксис
handleClick = () => {
- console.log('this is:', this);
+ console.log('значение this:', this);
}
render() {
return (
- Click me
+ Кликни по мне
);
}
}
```
-This syntax is enabled by default in [Create React App](https://github.com/facebookincubator/create-react-app).
+Такой синтаксис доступен в [Create React App](https://github.com/facebookincubator/create-react-app) по умолчанию.
-If you aren't using class fields syntax, you can use an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in the callback:
+Если вы не пользуетесь синтаксисом полей, можете попробовать [стрелочные функции](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions) в колбэке:
```js{7-9}
class LoggingButton extends React.Component {
handleClick() {
- console.log('this is:', this);
+ console.log('значение this:', this);
}
render() {
- // This syntax ensures `this` is bound within handleClick
+ // Такой синтаксис гарантирует, что `this` привязан к handleClick.
return (
this.handleClick(e)}>
- Click me
+ Кликни по мне
);
}
}
```
-The problem with this syntax is that a different callback is created each time the `LoggingButton` renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
+Проблема этого синтаксиса в том, что при каждом рендере `LoggingButton` создается новый колбэк. Чаще всего это не страшно. Однако, если этот колбэк попадает как проп в дочерние компоненты, эти компоненты могут быть отрендерены снова. Мы рекомендуем делать привязку в конструкторе или использовать синтаксис полей классов, чтобы избежать проблем с производительностью.
-## Passing Arguments to Event Handlers {#passing-arguments-to-event-handlers}
+## Передача аргументов в обработчики событий {#passing-arguments-to-event-handlers}
-Inside a loop it is common to want to pass an extra parameter to an event handler. For example, if `id` is the row ID, either of the following would work:
+Внутри цикла часто нужно передать дополнительный аргумент в обработчик события. Например, если `id` — это идентификатор строки, можно использовать следующие варианты:
```js
- this.deleteRow(id, e)}>Delete Row
-Delete Row
+ this.deleteRow(id, e)}>Удалить строку
+Удалить строку
```
-The above two lines are equivalent, and use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and [`Function.prototype.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) respectively.
+Две строки выше — эквивалентны, и используют [стрелочные функции](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions) и [`Function.prototype.bind`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) соответственно.
-In both cases, the `e` argument representing the React event will be passed as a second argument after the ID. With an arrow function, we have to pass it explicitly, but with `bind` any further arguments are automatically forwarded.
+В обоих случаях аргумент `e`, представляющий событие React, будет передан как второй аргумент после идентификатора. Используя стрелочную функцию, необходимо передавать аргумент явно, но с `bind` любые последующие аргументы передаются автоматически.
diff --git a/content/docs/hello-world.md b/content/docs/hello-world.md
index 2fff80254..ab5f765e1 100644
--- a/content/docs/hello-world.md
+++ b/content/docs/hello-world.md
@@ -6,7 +6,7 @@ prev: cdn-links.html
next: introducing-jsx.html
---
-The smallest React example looks like this:
+Самый маленький пример на React выглядит так:
```js
ReactDOM.render(
@@ -15,36 +15,34 @@ ReactDOM.render(
);
```
-It displays a heading saying "Hello, world!" on the page.
+На странице появится заголовок «Hello, world!».
[](codepen://hello-world)
-Click the link above to open an online editor. Feel free to make some changes, and see how they affect the output. Most pages in this guide will have editable examples like this one.
+По ссылке выше находится онлайн-редактор. Попробуйте отредактировать код и посмотрите, как изменится результат. Мы ещё увидим много таких интерактивных примеров.
+## Как читать это руководство {#how-to-read-this-guide}
-## How to Read This Guide {#how-to-read-this-guide}
+В этом руководстве мы рассмотрим строительные блоки React-приложений: элементы и компоненты. Освоив их, вы сможете создавать сложные приложения из маленьких повторно используемых частей.
-In this guide, we will examine the building blocks of React apps: elements and components. Once you master them, you can create complex apps from small reusable pieces.
-
->Tip
+>Совет
>
->This guide is designed for people who prefer **learning concepts step by step**. If you prefer to learn by doing, check out our [practical tutorial](/tutorial/tutorial.html). You might find this guide and the tutorial complementary to each other.
+>Это руководство предназначено для людей, которые предпочитают **изучать базовые понятия шаг за шагом**. Если вы предпочитаете учиться на практике, ознакомьтесь с нашим [практическим введением](/tutorial/tutorial.html). Учебник и руководство в чем-то дополняют друг друга.
-This is the first chapter in a step-by-step guide about main React concepts. You can find a list of all its chapters in the navigation sidebar. If you're reading this from a mobile device, you can access the navigation by pressing the button in the bottom right corner of your screen.
+Это первая глава в пошаговом руководстве про основные понятия в React. Оглавление находится в боковой панели. Если вы читаете руководство с мобильного устройства, открыть навигационное меню можно, если нажать кнопку в правом нижнем углу экрана.
-Every chapter in this guide builds on the knowledge introduced in earlier chapters. **You can learn most of React by reading the “Main Concepts” guide chapters in the order they appear in the sidebar.** For example, [“Introducing JSX”](/docs/introducing-jsx.html) is the next chapter after this one.
+Каждая глава в этом руководстве опирается на знания из предыдущей. **Большую часть React можно изучить, прочитав главы руководства «Основные понятия» в том порядке, в котором они перечислены на боковой панели.** Например, [«Знакомство с JSX»](/docs/introducing-jsx.html) — следующая глава.
-## Knowledge Level Assumptions {#knowledge-level-assumptions}
+## Необходимый уровень знаний {#knowledge-level-assumptions}
-React is a JavaScript library, and so we'll assume you have a basic understanding of the JavaScript language. **If you don't feel very confident, we recommend [going through a JavaScript tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) to check your knowledge level** and enable you to follow along this guide without getting lost. It might take you between 30 minutes and an hour, but as a result you won't have to feel like you're learning both React and JavaScript at the same time.
+React — это библиотека JavaScript, поэтому мы предполагаем, что у вас есть базовое понимание языка JavaScript. **Если вы чувствуете себя неуверенно, мы рекомендуем [прочесть введение в JavaScript](https://developer.mozilla.org/ru/docs/Web/JavaScript/A_re-introduction_to_JavaScript) для проверки своих знаний**; оно облегчит чтение руководства по React. Это займёт от 30 минут до часа, но в результате у вас не будет ощущения, что вы одновременно изучаете и React, и JavaScript.
->Note
+>Примечание
>
->This guide occasionally uses some of the newer JavaScript syntax in the examples. If you haven't worked with JavaScript in the last few years, [these three points](https://gist.github.com/gaearon/683e676101005de0add59e8bb345340c) should get you most of the way.
-
+>В примерах руководства иногда используются новый синтаксис JavaScript. Если вы не работали с JavaScript в последние несколько лет, [эти три пункта](https://gist.github.com/gaearon/683e676101005de0add59e8bb345340c) должны помочь вам.
-## Let's Get Started! {#lets-get-started}
+## Начинаем! {#lets-get-started}
-Keep scrolling down, and you'll find the link to the [next chapter of this guide](/docs/introducing-jsx.html) right before the website footer.
+Прокрутите страницу немного ниже, чтобы перейти к [следующей главе руководства](/docs/introducing-jsx.html).
diff --git a/content/docs/higher-order-components.md b/content/docs/higher-order-components.md
index 63da3ef86..62aeca5d2 100644
--- a/content/docs/higher-order-components.md
+++ b/content/docs/higher-order-components.md
@@ -1,32 +1,32 @@
---
id: higher-order-components
-title: Higher-Order Components
+title: Компоненты высшего порядка
permalink: docs/higher-order-components.html
---
-A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature.
+Компонент высшего порядка (Higher-Order Component, HOC) -- это один из продвинутых способов для повторного использования логики. HOC не являются частью API React, но часто применяются из-за композиционной природы компонентов.
-Concretely, **a higher-order component is a function that takes a component and returns a new component.**
+Говоря просто, **компонент высшего порядка -- это функция, которая принимает компонент и возвращает новый компонент.**
```js
const EnhancedComponent = higherOrderComponent(WrappedComponent);
```
-Whereas a component transforms props into UI, a higher-order component transforms a component into another component.
+Если обычный компонент преобразует пропсы в UI, то компонент высшего порядка преобразует компонент в другой компонент.
-HOCs are common in third-party React libraries, such as Redux's [`connect`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options) and Relay's [`createFragmentContainer`](http://facebook.github.io/relay/docs/en/fragment-container.html).
+HOC часто встречаются в сторонних библиотеках, например [`connect`](https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#connect) в Redux и [`createFragmentContainer`](https://facebook.github.io/relay/docs/en/fragment-container.html) в Relay.
-In this document, we'll discuss why higher-order components are useful, and how to write your own.
+В этой главе мы обсудим чем полезны компоненты высшего порядка и как их создавать.
-## Use HOCs For Cross-Cutting Concerns {#use-hocs-for-cross-cutting-concerns}
+## HOC для сквозной функциональности {#use-hocs-for-cross-cutting-concerns}
-> **Note**
+> **Примечание**
>
-> We previously recommended mixins as a way to handle cross-cutting concerns. We've since realized that mixins create more trouble than they are worth. [Read more](/blog/2016/07/13/mixins-considered-harmful.html) about why we've moved away from mixins and how you can transition your existing components.
+> В прошлом мы рекомендовали примеси для реализации сквозной функциональности, но со временем выяснилось, что от них больше вреда, чем пользы. [Узнайте](/blog/2016/07/13/mixins-considered-harmful.html), почему мы решили убрать примеси и как переписать старые компоненты.
-Components are the primary unit of code reuse in React. However, you'll find that some patterns aren't a straightforward fit for traditional components.
+Традиционные компоненты подразумевают многократное использование, но не позволяют с лёгкостью решить некоторые проблемы.
-For example, say you have a `CommentList` component that subscribes to an external data source to render a list of comments:
+Рассмотрим пример `CommentList`, который получает список комментариев из внешнего источника данных и отображает их:
```js
class CommentList extends React.Component {
@@ -34,23 +34,23 @@ class CommentList extends React.Component {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
- // "DataSource" is some global data source
+ // "DataSource" -- произвольный глобальный источник данных
comments: DataSource.getComments()
};
}
componentDidMount() {
- // Subscribe to changes
+ // Подписаться на оповещения
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
- // Clean up listener
+ // Отписаться от оповещений
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
- // Update component state whenever the data source changes
+ // Сохранить комментарии из внешнего источника в локальном состоянии
this.setState({
comments: DataSource.getComments()
});
@@ -68,7 +68,7 @@ class CommentList extends React.Component {
}
```
-Later, you write a component for subscribing to a single blog post, which follows a similar pattern:
+Теперь мы решили реализовать новый компонент, который отслеживает изменения конкретной публикации и повторяет уже знакомый нам шаблон:
```js
class BlogPost extends React.Component {
@@ -100,15 +100,15 @@ class BlogPost extends React.Component {
}
```
-`CommentList` and `BlogPost` aren't identical — they call different methods on `DataSource`, and they render different output. But much of their implementation is the same:
+Разница между `CommentList` и `BlogPost` в том, что они вызывают разные методы `DataSource` и рендерят разный вывод. Однако в большинстве своём они похожи:
-- On mount, add a change listener to `DataSource`.
-- Inside the listener, call `setState` whenever the data source changes.
-- On unmount, remove the change listener.
+- Оба компонента подписываются на оповещения от `DataSource` при монтировании.
+- Оба меняют внутреннее состояние при изменении `DataSource`.
+- Оба отписываются от `DataSource` при размонтировании.
-You can imagine that in a large app, this same pattern of subscribing to `DataSource` and calling `setState` will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.
+Можете представить, что в больших приложениях связка «подписаться на `DataSource`, затем вызвать `setState`» повторяется очень часто. Было бы здорово абстрагировать эту функциональность и использовать ее в других компонентах.
-We can write a function that creates components, like `CommentList` and `BlogPost`, that subscribe to `DataSource`. The function will accept as one of its arguments a child component that receives the subscribed data as a prop. Let's call the function `withSubscription`:
+Давайте реализуем функцию `withSubscription` -- она будет создавать компоненты и подписывать их на обновления `DataSource` (наподобие `CommentList` и `BlogPost`). Функция будет принимать оборачиваемый компонент и через пропсы передавать ему новые данные:
```js
const CommentListWithSubscription = withSubscription(
@@ -122,14 +122,14 @@ const BlogPostWithSubscription = withSubscription(
);
```
-The first parameter is the wrapped component. The second parameter retrieves the data we're interested in, given a `DataSource` and the current props.
+Первый параметр -- это оборачиваемый компонент. Второй -- функция, которая извлекает нужные нам данные, она получает `DataSource` и текущие пропсы.
-When `CommentListWithSubscription` and `BlogPostWithSubscription` are rendered, `CommentList` and `BlogPost` will be passed a `data` prop with the most current data retrieved from `DataSource`:
+Когда `CommentListWithSubscription` и `BlogPostWithSubscription` рендерятся, они передают в `CommentList` и `BlogPost` обновлённые данные `DataSource` через проп `data`:
```js
-// This function takes a component...
+// Это функция принимает компонент...
function withSubscription(WrappedComponent, selectData) {
- // ...and returns another component...
+ // ...и возвращает другой компонент...
return class extends React.Component {
constructor(props) {
super(props);
@@ -140,7 +140,7 @@ function withSubscription(WrappedComponent, selectData) {
}
componentDidMount() {
- // ... that takes care of the subscription...
+ // ...который подписывется на оповещения...
DataSource.addChangeListener(this.handleChange);
}
@@ -155,83 +155,80 @@ function withSubscription(WrappedComponent, selectData) {
}
render() {
- // ... and renders the wrapped component with the fresh data!
- // Notice that we pass through any additional props
+ // ... и рендерит оборачиваемый компонент со свежими данными!
+ // Обратите внимание, что мы передаем остальные пропсы
return ;
}
};
}
```
-Note that a HOC doesn't modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC *composes* the original component by *wrapping* it in a container component. A HOC is a pure function with zero side-effects.
+Заметьте, что HOC ничего не меняет и не наследует поведение оборачиваемого компонента, вместо этого HOC *оборачивает* оригинальный компонент в контейнер посредством *композиции*. HOC является чистой функцией без побочных эффектов.
-And that's it! The wrapped component receives all the props of the container, along with a new prop, `data`, which it uses to render its output. The HOC isn't concerned with how or why the data is used, and the wrapped component isn't concerned with where the data came from.
+Вот и всё! Оборачиваемый компонент получает все пропсы, переданные контейнеру, а также проп `data`. Для HOC не важно, как будут использоваться данные, а оборачиваемому компоненту не важно, откуда они берутся.
-Because `withSubscription` is a normal function, you can add as many or as few arguments as you like. For example, you may want to make the name of the `data` prop configurable, to further isolate the HOC from the wrapped component. Or you could accept an argument that configures `shouldComponentUpdate`, or one that configures the data source. These are all possible because the HOC has full control over how the component is defined.
+Так как `withSubscription` -- это обычная функция, то мы можем убрать или добавить любое количество аргументов. Например, мы могли бы сделать конфигурируемым название пропа `data` и ещё больше изолировать HOC от оборачиваемого компонента. Также мы можем добавить аргумент для конфигурации `shouldComponentUpdate` или источника данных. Всё это возможно, потому что HOC полностью контролирует процесс создания компонента.
-Like components, the contract between `withSubscription` and the wrapped component is entirely props-based. This makes it easy to swap one HOC for a different one, as long as they provide the same props to the wrapped component. This may be useful if you change data-fetching libraries, for example.
+Взаимодействие между `withSubscription` и оборачиваемым компонентом осуществляется с помощью пропсов, так же, как и между обычными компонентами. Благодаря этому мы можем с лёгкостью заменить один HOC на другой, при условии, что они передают одни и те же пропсы в оборачиваемый компонент. Это может пригодиться если, например, мы решим поменять библиотеку получения данных.
-## Don't Mutate the Original Component. Use Composition. {#dont-mutate-the-original-component-use-composition}
+## Не мутируйте оборачиваемый компонент. Используйте композицию. {#dont-mutate-the-original-component-use-composition}
-Resist the temptation to modify a component's prototype (or otherwise mutate it) inside a HOC.
+Не поддавайтесь соблазну менять прототип компонента (или мутировать его любым другим способом) внутри HOC.
```js
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
- console.log('Current props: ', this.props);
- console.log('Next props: ', nextProps);
+ console.log('Текущие пропсы: ', this.props);
+ console.log('Следующие пропсы: ', nextProps);
};
- // The fact that we're returning the original input is a hint that it has
- // been mutated.
+ // Если мы возвращаем оборачиваемый компонент, значит, наверняка мы его изменили
return InputComponent;
}
-// EnhancedComponent will log whenever props are received
+// EnhancedComponent будет печатать в консоль при каждом изменении пропсов
const EnhancedComponent = logProps(InputComponent);
```
-There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component. More crucially, if you apply another HOC to `EnhancedComponent` that *also* mutates `componentWillReceiveProps`, the first HOC's functionality will be overridden! This HOC also won't work with function components, which do not have lifecycle methods.
+В приведённом выше примере мы не можем повторно использовать `InputComponent` отдельно от `EnhancedComponent`. Важнее то, что если мы захотим обернуть `EnhancedComponent` в другой HOC, который *тоже* меняет `componentWillReceiveProps`, то мы сотрём функциональность заданную первым HOC! Более того, `EnhancedComponent` не работает с функциональными компонентами, потому что у них отсутствуют методы жизненного цикла.
-Mutating HOCs are a leaky abstraction—the consumer must know how they are implemented in order to avoid conflicts with other HOCs.
+Мутирующие HOC являются хрупкой абстракцией, они конфликтуют с другими HOC, мы не сможем просто применять их без того, чтобы знать что именно они меняют.
-Instead of mutation, HOCs should use composition, by wrapping the input component in a container component:
+Вместо мутации, компоненты высшего порядка должны применять композицию, оборачивая компонент в контейнер:
```js
function logProps(WrappedComponent) {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
- console.log('Current props: ', this.props);
- console.log('Next props: ', nextProps);
+ console.log('Текущие пропсы: ', this.props);
+ console.log('Следующие пропсы: ', nextProps);
}
render() {
- // Wraps the input component in a container, without mutating it. Good!
+ // Оборачиваем компонент в контейнер без мутаций. Супер!
return ;
}
}
}
```
-This HOC has the same functionality as the mutating version while avoiding the potential for clashes. It works equally well with class and function components. And because it's a pure function, it's composable with other HOCs, or even with itself.
+Этот HOC обладает такой же функциональностью, как и предыдущий, но не создаёт конфликтов с другими HOC и работает как с функциональными, так и с классовыми компонентами. Более того, HOC реализован с помощью чистой функции, поэтому его можно совмещать с другими HOC, или даже самого с собой.
-You may have noticed similarities between HOCs and a pattern called **container components**. Container components are part of a strategy of separating responsibility between high-level and low-level concerns. Containers manage things like subscriptions and state, and pass props to components that handle things like rendering UI. HOCs use containers as part of their implementation. You can think of HOCs as parameterized container component definitions.
+Возможно, вы уже заметили сходство между HOC и **компонентами-контейнерами**. Напомним, что при помощи контейнеров мы обычно разделяем общую функциональность от частной. Например, в контейнере мы будем управлять внутренним состоянием или подпиской на внешние ресурсы, и через пропсы передавать данные в компоненты, ответственные за рендер UI. При реализации HOС мы тоже используем контейнеры. Можно сказать что HOC -- это инструмент для параметризированного создания контейнеров.
-## Convention: Pass Unrelated Props Through to the Wrapped Component {#convention-pass-unrelated-props-through-to-the-wrapped-component}
+## Соглашение: передавайте посторонние пропсы оборачиваемому компоненту {#convention-pass-unrelated-props-through-to-the-wrapped-component}
-HOCs add features to a component. They shouldn't drastically alter its contract. It's expected that the component returned from a HOC has a similar interface to the wrapped component.
+HOC добавляют компонентам функциональность, но они не должны менять их оригинальное предназначение. Ожидается, что интерфейс компонента, который вы возвращаете из HOC, будет похож на интерфейс оборачиваемого компонента.
-HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this:
+Пропсы, которые напрямую не связаны с функциональностью HOC, должны передаваться без изменений оборачиваемому компоненту. Рендер-метод большинства HOC похож на следующий:
```js
render() {
- // Filter out extra props that are specific to this HOC and shouldn't be
- // passed through
+ // Отфильтруйте пропсы применимые только к этому HOC и которые не нужно передавать дальше
const { extraProp, ...passThroughProps } = this.props;
- // Inject props into the wrapped component. These are usually state values or
- // instance methods.
+ // Добавьте новые пропсы в оборачиваемый компонент. Обычно мы передаем значения состояния или методы экземпляра
const injectedProp = someStateOrInstanceMethod;
- // Pass props to wrapped component
+ // Передайте пропсы в оборачиваемый компонент
return (
Component`. Functions whose output type is the same as its input type are really easy to compose together.
+Такая форма может показаться запутанной и ненужной, но есть и преимущества. Вызов `connect` возвращает HOC с подписью `Component => Component`. Функции с одинаковым типом результата и единственного аргумента легко совмещаются в композиции.
```js
-// Instead of doing this...
+// Вместо этого...
const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent))
-// ... you can use a function composition utility
-// compose(f, g, h) is the same as (...args) => f(g(h(...args)))
+// ... вы можете воспользоваться вспомогательной совмещающей функцией
+// compose(f, g, h) идентичен (...args) => f(g(h(...args)))
const enhance = compose(
- // These are both single-argument HOCs
+ // Оба параметра являются HOC и принимают один единственный аргумент
withRouter,
connect(commentSelector)
)
const EnhancedComponent = enhance(WrappedComponent)
```
-(This same property also allows `connect` and other enhancer-style HOCs to be used as decorators, an experimental JavaScript proposal.)
+(Поэтому мы можем использовать `connect` и другие расширяющие функциональность HOC в качестве экспериментальных JavaScript декораторов.)
-The `compose` utility function is provided by many third-party libraries including lodash (as [`lodash.flowRight`](https://lodash.com/docs/#flowRight)), [Redux](http://redux.js.org/docs/api/compose.html), and [Ramda](http://ramdajs.com/docs/#compose).
+Вы можете найти вспомогательную функцию `compose` во многих сторонних библиотеках, включая lodash (под названием [`lodash.flowRight`](https://lodash.com/docs/#flowRight)), [Redux](https://redux.js.org/docs/api/compose.html), и [Ramda](https://ramdajs.com/docs/#compose).
-## Convention: Wrap the Display Name for Easy Debugging {#convention-wrap-the-display-name-for-easy-debugging}
+## Соглашение: добавьте отображаемое имя для легкой отладки {#convention-wrap-the-display-name-for-easy-debugging}
-The container components created by HOCs show up in the [React Developer Tools](https://github.com/facebook/react-devtools) like any other component. To ease debugging, choose a display name that communicates that it's the result of a HOC.
+Созданные HOC компоненты-контейнеры отображаются в консоли [инструментов разработки React](https://github.com/facebook/react-devtools) наряду с другими компонентами. Для более лёгкой отладки вы можете задать имя, которое подскажет, что определенный компонент был создан с помощью HOC.
-The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named `withSubscription`, and the wrapped component's display name is `CommentList`, use the display name `WithSubscription(CommentList)`:
+Самый распространённый способ -- это обернуть имя оборачиваемого компонента. Например, если вы назвали компонент высшего порядка `withSubscription`, а имя оборачиваемого компонента было `CommentList`, то отображаемое имя будет `WithSubscription(CommentList)`:
```js
function withSubscription(WrappedComponent) {
@@ -313,61 +310,60 @@ function getDisplayName(WrappedComponent) {
}
```
+## Предостережения {#caveats}
-## Caveats {#caveats}
-
-Higher-order components come with a few caveats that aren't immediately obvious if you're new to React.
+Вы можете столкнуться с неочевидными проблемами, когда работаете с компонентами высшего порядка.
-### Don't Use HOCs Inside the render Method {#dont-use-hocs-inside-the-render-method}
+### Не используйте HOC внутри рендер-метода {#dont-use-hocs-inside-the-render-method}
-React's diffing algorithm (called reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from `render` is identical (`===`) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they're not equal, the previous subtree is unmounted completely.
+Алгоритм сравнения React (известный как согласование или reconciliation) использует тождественность компонентов чтобы определить нужно ли обновить существующее поддерево, или убрать и монтировать вместо него новое. Если компонент, полученный из `render`, идентичен (`===`) компоненту из предыдущего рендера, то React рекурсивно продолжит сравнивать поддерево. Если компоненты не равны, React полностью удалит и заменит старое поддерево.
-Normally, you shouldn't need to think about this. But it matters for HOCs because it means you can't apply a HOC to a component within the render method of a component:
+Обычно нас это не беспокоит. Однако, важно учитывать что мы не можем применять компоненты высшего порядка внутри рендер-метода компонента:
```js
render() {
- // A new version of EnhancedComponent is created on every render
+ // Мы создаём новую версию EnhancedComponent при каждом рендере
// EnhancedComponent1 !== EnhancedComponent2
const EnhancedComponent = enhance(MyComponent);
- // That causes the entire subtree to unmount/remount each time!
+ // Мы каждый раз размонтируем и монтируем целиком всё поддерево!
return ;
}
```
-The problem here isn't just about performance — remounting a component causes the state of that component and all of its children to be lost.
+Проблема не только в производительности. Повторное монтирование компонента обнуляет его состояние, а также состояние его дочерних компонентов.
-Instead, apply HOCs outside the component definition so that the resulting component is created only once. Then, its identity will be consistent across renders. This is usually what you want, anyway.
+Не применяйте HOC в определении другого компонента. Сначала нужно отдельно получить компонент из HOC, и только потом использовать его. Таким образом React будет сравнивать один и тот же компонент при повторном рендере.
-In those rare cases where you need to apply a HOC dynamically, you can also do it inside a component's lifecycle methods or its constructor.
+При необходимости (в редких случаях) можно динамически применять HOC в методах жизненного цикла или конструкторе компонента.
-### Static Methods Must Be Copied Over {#static-methods-must-be-copied-over}
+### Копируйте статические методы {#static-methods-must-be-copied-over}
-Sometimes it's useful to define a static method on a React component. For example, Relay containers expose a static method `getFragment` to facilitate the composition of GraphQL fragments.
+Иногда бывает полезно определить статические методы компонента. Например, статический метод `getFragment` библиотеки Relay позволяет составить композицию из фрагментов данных GraphQL.
-When you apply a HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component.
+Когда мы применяем HOC, то заворачиваем оригинальный компонент в контейнер. Поэтому у нового компонента не будет статических методов оригинального компонента.
```js
-// Define a static method
+// Определим статический метод
WrappedComponent.staticMethod = function() {/*...*/}
-// Now apply a HOC
+// Теперь применим HOC
const EnhancedComponent = enhance(WrappedComponent);
-// The enhanced component has no static method
+// У расширенного компонента нет статических методов
typeof EnhancedComponent.staticMethod === 'undefined' // true
```
-To solve this, you could copy the methods onto the container before returning it:
+Скопируйте недостающие методы в контейнер:
```js
function enhance(WrappedComponent) {
class Enhance extends React.Component {/*...*/}
- // Must know exactly which method(s) to copy :(
+ // Мы должны точно знать какие методы копировать :(
Enhance.staticMethod = WrappedComponent.staticMethod;
return Enhance;
}
```
-However, this requires you to know exactly which methods need to be copied. You can use [hoist-non-react-statics](https://github.com/mridgway/hoist-non-react-statics) to automatically copy all non-React static methods:
+К сожалению, вы должны точно знать какие методы копировать. Вы можете воспользоваться [hoist-non-react-statics](https://github.com/mridgway/hoist-non-react-statics), чтобы автоматически скопировать не связанные с React статические методы:
```js
import hoistNonReactStatic from 'hoist-non-react-statics';
@@ -378,22 +374,22 @@ function enhance(WrappedComponent) {
}
```
-Another possible solution is to export the static method separately from the component itself.
+Другое возможное решение -- экспортировать статические методы отдельно от компонента.
```js
-// Instead of...
+// Вместо...
MyComponent.someFunction = someFunction;
export default MyComponent;
-// ...export the method separately...
+// ...отдельно экспортируйте метод...
export { someFunction };
-// ...and in the consuming module, import both
+// ...в модуле-потребителе мы можем использовать оба экспорта
import MyComponent, { someFunction } from './MyComponent.js';
```
-### Refs Aren't Passed Through {#refs-arent-passed-through}
+### Рефы не передаются {#refs-arent-passed-through}
-While the convention for higher-order components is to pass through all props to the wrapped component, this does not work for refs. That's because `ref` is not really a prop — like `key`, it's handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component.
+По соглашению компоненты высшего порядка передают оборачеваемому компоненту все пропсы, кроме рефов. `ref` на самом деле не проп, как, например, `key`, и поэтому иначе обрабатывается React. Реф элемента, созданного компонентом из HOC, будет указывать на экземпляр ближайшего в иерархии контейнера, а не на оборачиваемый компонент.
-The solution for this problem is to use the `React.forwardRef` API (introduced with React 16.3). [Learn more about it in the forwarding refs section](/docs/forwarding-refs.html).
\ No newline at end of file
+Вы можете решить эту проблему с помощью API-метода `React.forwardRef` (добавлен в React 16.3). [Узнать подробнее в главе Перенаправление рефов](/docs/forwarding-refs.html).
diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md
index d7e304d55..ea862cbce 100644
--- a/content/docs/hooks-faq.md
+++ b/content/docs/hooks-faq.md
@@ -192,7 +192,7 @@ There are a few more heuristics, and they might change over time as we fine-tune
### How do lifecycle methods correspond to Hooks? {#how-do-lifecycle-methods-correspond-to-hooks}
-* `constructor`: Function components don't need a constructor. You can initialize the state in the [`useState`](/docs/hooks-reference.html#usestate) call. If computing it is expensive, you can pass a function to `useState`.
+* `constructor`: Function components don't need a constructor. You can initialize the state in the [`useState`](/docs/hooks-reference.html#usestate) call. If computing is expensive, you can pass a function to `useState`.
* `getDerivedStateFromProps`: Schedule an update [while rendering](#how-do-i-implement-getderivedstatefromprops) instead.
@@ -356,13 +356,13 @@ function Counter() {
const calculation = count * 100;
const prevCalculation = usePrevious(calculation);
// ...
- ```
+```
It's possible that in the future React will provide a `usePrevious` Hook out of the box since it's a relatively common use case.
See also [the recommended pattern for derived state](#how-do-i-implement-getderivedstatefromprops).
-### How do I implement `getDerivedStateFromProps`?
+### How do I implement `getDerivedStateFromProps`? {#how-do-i-implement-getderivedstatefromprops}
While you probably [don't need it](/blog/2018/06/07/you-probably-dont-need-derived-state.html), in rare cases that you do (such as implementing a `` component), you can update the state right during rendering. React will re-run the component with updated state immediately after exiting the first render so it wouldn't be expensive.
@@ -385,7 +385,7 @@ function ScrollView({row}) {
This might look strange at first, but an update during rendering is exactly what `getDerivedStateFromProps` has always been like conceptually.
-### Is there something like forceUpdate?
+### Is there something like forceUpdate? {#is-there-something-like-forceupdate}
Both `useState` and `useReducer` Hooks [bail out of updates](/docs/hooks-reference.html#bailing-out-of-a-state-update) if the next value is the same as the previous one. Mutating state in place and calling `setState` will not cause a re-render.
@@ -401,22 +401,22 @@ Normally, you shouldn't mutate local state in React. However, as an escape hatch
Try to avoid this pattern if possible.
-### Can I make a ref to a function component?
+### Can I make a ref to a function component? {#can-i-make-a-ref-to-a-function-component}
While you shouldn't need this often, you may expose some imperative methods to a parent component with the [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle) Hook.
-### What does `const [thing, setThing] = useState()` mean?
+### What does `const [thing, setThing] = useState()` mean? {#what-does-const-thing-setthing--usestate-mean}
If you're not familiar with this syntax, check out the [explanation](/docs/hooks-state.html#tip-what-do-square-brackets-mean) in the State Hook documentation.
-## Performance Optimizations
+## Performance Optimizations {#performance-optimizations}
-### Can I skip an effect on updates?
+### Can I skip an effect on updates? {#can-i-skip-an-effect-on-updates}
Yes. See [conditionally firing an effect](/docs/hooks-reference.html#conditionally-firing-an-effect). Note that forgetting to handle updates often [introduces bugs](/docs/hooks-effect.html#explanation-why-effects-run-on-each-update), which is why this isn't the default behavior.
-### How do I implement `shouldComponentUpdate`?
+### How do I implement `shouldComponentUpdate`? {#how-do-i-implement-shouldcomponentupdate}
You can wrap a function component with `React.memo` to shallowly compare its props:
@@ -431,7 +431,7 @@ It's not a Hook because it doesn't compose like Hooks do. `React.memo` is equiva
`React.memo` doesn't compare state because there is no single state object to compare. But you can make children pure too, or even [optimize individual children with `useMemo`](/docs/hooks-faq.html#how-to-memoize-calculations).
-### How to memoize calculations?
+### How to memoize calculations? {#how-to-memoize-calculations}
The [`useMemo`](/docs/hooks-reference.html#usememo) Hook lets you cache calculations between multiple renders by "remembering" the previous computation:
@@ -464,9 +464,9 @@ function Parent({ a, b }) {
Note that this approach won't work in a loop because Hook calls [can't](/docs/hooks-rules.html) be placed inside loops. But you can extract a separate component for the list item, and call `useMemo` there.
-### How to create expensive objects lazily?
+### How to create expensive objects lazily? {#how-to-create-expensive-objects-lazily}
-`useMemo` lets you [memoize an expensive calculation](#how-to-memoize-calculations) if the inputs are the same. However, it only serves as a hint, and doesn't *guarantee* the computation won't re-run. But sometimes need to be sure an object is only created once.
+`useMemo` lets you [memoize an expensive calculation](#how-to-memoize-calculations) if the inputs are the same. However, it only serves as a hint, and doesn't *guarantee* the computation won't re-run. But sometimes you need to be sure an object is only created once.
**The first common use case is when creating the initial state is expensive:**
@@ -525,7 +525,7 @@ function Image(props) {
This avoids creating an expensive object until it's truly needed for the first time. If you use Flow or TypeScript, you can also give `getObserver()` a non-nullable type for convenience.
-### Are Hooks slow because of creating functions in render?
+### Are Hooks slow because of creating functions in render? {#are-hooks-slow-because-of-creating-functions-in-render}
No. In modern browsers, the raw performance of closures compared to classes doesn't differ significantly except in extreme scenarios.
@@ -550,7 +550,7 @@ Traditionally, performance concerns around inline functions in React have been r
* Finally, the `useReducer` Hook reduces the need to pass callbacks deeply, as explained below.
-### How to avoid passing callbacks down?
+### How to avoid passing callbacks down? {#how-to-avoid-passing-callbacks-down}
We've found that most people don't enjoy manually passing callbacks through every level of a component tree. Even though it is more explicit, it can feel like a lot of "plumbing".
@@ -560,7 +560,7 @@ In large component trees, an alternative we recommend is to pass down a `dispatc
const TodosDispatch = React.createContext(null);
function TodosApp() {
- // Tip: `dispatch` won't change between re-renders
+ // Note: `dispatch` won't change between re-renders
const [todos, dispatch] = useReducer(todosReducer);
return (
@@ -592,7 +592,7 @@ This is both more convenient from the maintenance perspective (no need to keep f
Note that you can still choose whether to pass the application *state* down as props (more explicit) or as context (more convenient for very deep updates). If you use context to pass down the state too, use two different context types -- the `dispatch` context never changes, so components that read it don't need to rerender unless they also need the application state.
-### How to read an often-changing value from `useCallback`?
+### How to read an often-changing value from `useCallback`? {#how-to-read-an-often-changing-value-from-usecallback}
>Note
>
@@ -662,15 +662,15 @@ function useEventCallback(fn, dependencies) {
In either case, we **don't recommend this pattern** and only show it here for completeness. Instead, it is preferable to [avoid passing callbacks deep down](#how-to-avoid-passing-callbacks-down).
-## Under the Hood
+## Under the Hood {#under-the-hood}
-### How does React associate Hook calls with components?
+### How does React associate Hook calls with components? {#how-does-react-associate-hook-calls-with-components}
React keeps track of the currently rendering component. Thanks to the [Rules of Hooks](/docs/hooks-rules.html), we know that Hooks are only called from React components (or custom Hooks -- which are also only called from React components).
There is an internal list of "memory cells" associated with each component. They're just JavaScript objects where we can put some data. When you call a Hook like `useState()`, it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple `useState()` calls each get independent local state.
-### What is the prior art for Hooks?
+### What is the prior art for Hooks? {#what-is-the-prior-art-for-hooks}
Hooks synthesize ideas from several different sources:
diff --git a/content/docs/hooks-intro.md b/content/docs/hooks-intro.md
index b4cefcfbe..c406d2ab4 100644
--- a/content/docs/hooks-intro.md
+++ b/content/docs/hooks-intro.md
@@ -1,17 +1,17 @@
---
id: hooks-intro
-title: Introducing Hooks
+title: Введение в хуки
permalink: docs/hooks-intro.html
next: hooks-overview.html
---
-*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
+*Хуки* — новая возможность в React 16.8, которая позволяет использовать состояние и другие возможности React без написания классов.
```js{4,5}
import React, { useState } from 'react';
function Example() {
- // Declare a new state variable, which we'll call "count"
+ // Объявление переменной состояния, которую мы назовём "count"
const [count, setCount] = useState(0);
return (
@@ -25,88 +25,86 @@ function Example() {
}
```
-This new function `useState` is the first "Hook" we'll learn about, but this example is just a teaser. Don't worry if it doesn't make sense yet!
+Первый хук, который мы изучим, это функция `useState`. Не беспокойтесь, если этот пример будет поначалу неясен. Скоро мы разберёмся, как он работает.
-**You can start learning Hooks [on the next page](/docs/hooks-overview.html).** On this page, we'll continue by explaining why we're adding Hooks to React and how they can help you write great applications.
+**Вы можете начать изучать хуки [на следующей странице](/docs/hooks-overview.html).** Здесь же мы расскажем, зачем мы добавили хуки в React, и как они помогут вам писать приложения.
->Note
+>Примечание
>
->React 16.8.0 is the first release to support Hooks. When upgrading, don't forget to update all packages, including React DOM. React Native will support Hooks in the next stable release.
+>React 16.8.0 это первый релиз, поддерживающий хуки. При обновлении версии, не забудьте обновить и все зависимости, включая React DOM. React Native будет поддерживать хуки в следующем стабильном релизе.
-## Video Introduction {#video-introduction}
+## Видео-представление {#video-introduction}
-At React Conf 2018, Sophie Alpert and Dan Abramov introduced Hooks, followed by Ryan Florence demonstrating how to refactor an application to use them. Watch the video here:
+На конференции React Conf 2018, Софи Алперт (Sophie Alpert) и Дэн Абрамов (Dan Abramov) представили хуки, а Райн Флоренс (Ryan Florence) показал, как их использовать в приложении. Видео конференции можно посмотреть здесь:
-## No Breaking Changes {#no-breaking-changes}
+## Полная обратная совместимость {#no-breaking-changes}
-Before we continue, note that Hooks are:
+Перед тем, как мы продолжим, обратите внимание, что хуки:
-* **Completely opt-in.** You can try Hooks in a few components without rewriting any existing code. But you don't have to learn or use Hooks right now if you don't want to.
-* **100% backwards-compatible.** Hooks don't contain any breaking changes.
-* **Available now.** Hooks are now available with the release of v16.8.0.
+* **Полностью на ваше усмотрение.** Вы можете попробовать хуки в одних компонентах, не изменяя код в других. Хуки не обязательно использовать или изучать прямо сейчас.
+* **100% обратно совместимы.** Хуки не содержат изменений, которые могут поломать ваш существующий код.
+* **Доступны прямо сейчас.** Хуки доступны с выходом версии 16.8.0.
-**There are no plans to remove classes from React.** You can read more about the gradual adoption strategy for Hooks in the [bottom section](#gradual-adoption-strategy) of this page.
+**Мы не планируем удалять классы из React.** Вы можете прочитать больше о стратегии постепенного внедрения хуков в [разделе ниже](#gradual-adoption-strategy).
-**Hooks don't replace your knowledge of React concepts.** Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them.
+**Хуки не меняют ваши знания о концепциях в React.** Вместо этого, хуки предоставляют более прямой доступ к API уже знакомых вам понятий: пропсов, состояния, контекста, рефов, и жизненного цикла. Мы также рассмотрим мощный способ компоновать эти понятия с помощью хуков.
-**If you just want to start learning Hooks, feel free to [jump directly to the next page!](/docs/hooks-overview.html)** You can also keep reading this page to learn more about why we're adding Hooks, and how we're going to start using them without rewriting our applications.
+**Чтобы начать изучать хуки, [перейдите на следующую страницу!](/docs/hooks-overview.html)** На этой странице мы расскажем о том, зачем нужны хуки, и как их использовать, не переписывая наши приложения.
-## Motivation {#motivation}
+## Мотивация {#motivation}
-Hooks solve a wide variety of seemingly unconnected problems in React that we've encountered over five years of writing and maintaining tens of thousands of components. Whether you're learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems.
+Хуки решают множество, казалось бы, несвязанных между собой, проблем в React, с которыми мы сталкивались в течение пяти лет написания и поддержки десятков тысяч компонентов. Если вы изучаете React, используете его ежедневно или используете другую библиотеку с похожим компонентным подходом, эти проблемы наверняка покажутся вам знакомыми.
-### It's hard to reuse stateful logic between components {#its-hard-to-reuse-stateful-logic-between-components}
+### Трудно переиспользовать логику состояний между компонентами {#its-hard-to-reuse-stateful-logic-between-components}
-React doesn't offer a way to "attach" reusable behavior to a component (for example, connecting it to a store). If you've worked with React for a while, you may be familiar with patterns like [render props](/docs/render-props.html) and [higher-order components](/docs/higher-order-components.html) that try to solve this. But these patterns require you to restructure your components when you use them, which can be cumbersome and make code harder to follow. If you look at a typical React application in React DevTools, you will likely find a "wrapper hell" of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could [filter them out in DevTools](https://github.com/facebook/react-devtools/pull/503), this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic.
+В React нет способа «присоединить» повторно используемое поведение к компоненту (например, подключение к хранилищу). Если вы работали с React какое-то время, то вам могут быть знакомы такие паттерны, как [рендер-пропсы](/docs/render-props.html) и [компоненты высшего порядка](/docs/higher-order-components.html), которые пытаются решить эту проблему. Но эти паттерны заставляют вас изменять структуру компонентов, что делает код громоздким и трудным в поддержке. Если вы посмотрите на типичное React-приложение в React DevTools, то увидите «ад обёрток» из компонентов, окружённых провайдерами, консьюмерами, компонентами высшего порядка, рендер-пропсами и другими абстракциями. Хоть мы и можем [отфильтровать их в DevTools](https://github.com/facebook/react-devtools/pull/503), всё это указывает на более глубокую проблему в React. Нужен более удобный способ повторно использовать логику вокруг состояния.
-With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. **Hooks allow you to reuse stateful logic without changing your component hierarchy.** This makes it easy to share Hooks among many components or with the community.
+С помощью хуков вы можете извлечь логику состояния из компонента, чтобы её протестировать или повторно использовать. **Хуки позволяют вам переиспользовать логику состояния, не затрагивая дерево компонентов.** Благодаря этому, хуки легко использовать в разных компонентах и делиться ими с сообществом.
-We'll discuss this more in [Building Your Own Hooks](/docs/hooks-custom.html).
+Мы обсудим это подробнее в разделе [Создание собственных хуков](/docs/hooks-custom.html).
-### Complex components become hard to understand {#complex-components-become-hard-to-understand}
+### Сложные компоненты становятся трудными для понимания {#complex-components-become-hard-to-understand}
-We've often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic. For example, components might perform some data fetching in `componentDidMount` and `componentDidUpdate`. However, the same `componentDidMount` method might also contain some unrelated logic that sets up event listeners, with cleanup performed in `componentWillUnmount`. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
+Нам часто приходилось поддерживать компоненты, которые изначально были простыми, но превратились в неуправляемый беспорядок, состоящий из логики состояния и побочных эффектов. Каждый метод жизненного цикла часто содержит смесь несвязанной логики. Например, компоненты могут загружать данные в `componentDidMount` и `componentDidUpdate`. Однако тот же метод `componentDidMount` может содержать несвязанную логику, которая добавляет обработчики события с отменой подписки в `componentWillUnmount`. Взаимосвязанный код, который изменяется вместе, разделяется, но совершенно несвязанный код в конечном итоге объединяется в один метод. Это легко приводит к багам и несоответствиям в приложении.
-In many cases it's not possible to break these components into smaller ones because the stateful logic is all over the place. It's also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library. However, that often introduces too much abstraction, requires you to jump between different files, and makes reusing components more difficult.
+В некоторых случаях невозможно разбить компоненты на более мелкие, потому что логика состояния раскидана повсюду. Такие компоненты сложно тестировать. Это одна из причин, по которой люди предпочитают использовать в React отдельную библиотеку для управления состоянием. Однако, это добавляет множество абстракций, заставляет прыгать между разными файлами и усложняет повторное использование компонентов.
-To solve this, **Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)**, rather than forcing a split based on lifecycle methods. You may also opt into managing the component's local state with a reducer to make it more predictable.
+Чтобы решить эту проблему, **хуки позволяют разбить один компонент на маленькие функции по их назначению (например, подписке или загрузке данных)**, а не на основе методов жизненного цикла. Вы также можете контролировать локальное состояние с помощью редюсера, чтобы поведение было более предсказуемым.
-We'll discuss this more in [Using the Effect Hook](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns).
+Мы обсудим это в разделе [использование эффект-хуков](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns).
-### Classes confuse both people and machines {#classes-confuse-both-people-and-machines}
+### Классы путают как людей, так и машины {#classes-confuse-both-people-and-machines}
-In addition to making code reuse and code organization more difficult, we've found that classes can be a large barrier to learning React. You have to understand how `this` works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable [syntax proposals](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/), the code is very verbose. People can understand props, state, and top-down data flow perfectly well but still struggle with classes. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.
+Вдобавок к усложнению организации кода и его переиспользования, классы создают существенный барьер в изучении React. Нужно понимать, как работает `this` в JavaScript, поведение которого отличается от большинства языков. Приходится помнить про привязку контекста для обработчиков событий. Без использования нестабильных [синтаксических предложений](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/), код становится многословным. Люди могут прекрасно понимать пропсы, состояние и однонаправленный поток данных, но всё равно путаться с классами. Различия между функциональными и классовыми компонентами в React и тем, когда их использовать, приводят к разногласиям даже между опытными React-разработчиками.
-Additionally, React has been out for about five years, and we want to make sure it stays relevant in the next five years. As [Svelte](https://svelte.technology/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/), and others show, [ahead-of-time compilation](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) of components has a lot of future potential. Especially if it's not limited to templates. Recently, we've been experimenting with [component folding](https://github.com/facebook/react/issues/7323) using [Prepack](https://prepack.io/), and we've seen promising early results. However, we found that class components can encourage unintentional patterns that make these optimizations fall back to a slower path. Classes present issues for today's tools, too. For example, classes don't minify very well, and they make hot reloading flaky and unreliable. We want to present an API that makes it more likely for code to stay on the optimizable path.
+Вдобавок, React существует уже около пяти лет и мы хотим убедиться, что он останется актуальным в течение следующих пяти лет. Как показывают [Svelte](https://svelte.technology/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/) и другие технологии, [компиляция компонентов перед их исполнением](https://ru.wikipedia.org/wiki/AOT-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D1%8F%D1%86%D0%B8%D1%8F) имеет огромный потенциал в будущем. Особенно, если шаблоны не накладывают ограничений. Недавно мы экспериментировали со [свёртыванием компонентов](https://github.com/facebook/react/issues/7323) с использованием [Prepack](https://prepack.io/) и увидели первые многообещающие результаты. Однако мы заметили, что классовые компоненты могут приводить к ненамеренным паттернам, сводящим оптимизации на нет. Классы создают сложности для инструментов и сегодня. Например, классы плохо минифицируются, а горячая перезагрузка (hot reloading) ненадёжна и часто ломает их. Наша цель — предоставить API, который повысит вероятность того, что код можно будет оптимизировать.
-To solve these problems, **Hooks let you use more of React's features without classes.** Conceptually, React components have always been closer to functions. Hooks embrace functions, but without sacrificing the practical spirit of React. Hooks provide access to imperative escape hatches and don't require you to learn complex functional or reactive programming techniques.
+Чтобы решить эти проблемы, **хуки позволяют использовать больше возможностей React без написания классов.** Концептуально, React-компоненты всегда были ближе к функциям. Хуки обеспечивают доступ к функционалу, но не обесценивают опыт использования React. Хуки предоставляют императивные лазейки и не требуют от вас изучения сложных функциональных или реактивных подходов.
->Examples
+>Примеры
>
->[Hooks at a Glance](/docs/hooks-overview.html) is a good place to start learning Hooks.
+>[Обзор хуков](/docs/hooks-overview.html) — хорошее начало для изучения хуков.
-## Gradual Adoption Strategy {#gradual-adoption-strategy}
+## Стратегия постепенного внедрения {#gradual-adoption-strategy}
->**TLDR: There are no plans to remove classes from React.**
+>**TLDR: Мы не планируем удалять классы из React.**
-We know that React developers are focused on shipping products and don't have time to look into every new API that's being released. Hooks are very new, and it might be better to wait for more examples and tutorials before considering learning or adopting them.
+Мы знаем, что React-разработчики сфокусированы на поставке продукта и у них нет времени изучать новый API каждого релиза. Хуки это что-то новое, и возможно, лучше подождать больше примеров и уроков, прежде чем начинать их изучение.
-We also understand that the bar for adding a new primitive to React is extremely high. For curious readers, we have prepared a [detailed RFC](https://github.com/reactjs/rfcs/pull/68) that dives into motivation with more details, and provides extra perspective on the specific design decisions and related prior art.
+Мы также понимаем, что планка для добавления новых примитивов в React очень высока. Поэтому для любопытных читателей мы подготовили [подробный RFC](https://github.com/reactjs/rfcs/pull/68), в котором можно найти больше информации о технических аспектах выбранного дизайна.
-**Crucially, Hooks work side-by-side with existing code so you can adopt them gradually.** We are sharing this experimental API to get early feedback from those in the community who are interested in shaping the future of React — and we will iterate on Hooks in the open.
+**Важно понимать, что хуки работают рядом с существущим кодом, поэтому вы можете внедрять их постепенно.** Нет спешки переходить на хуки. Мы рекомендуем избегать любых «больших переписываний», особенно для существующих, сложных классовых компонентов. Вам потребуется немного изменить мировоззрение, чтобы начать «мыслить хуками». По нашему опыту, лучше всего сначала попрактиковаться использовать хуки в новых и некритичных компонентах и убедиться, что все в вашей команде чувствуют себя комфортно с ними. После того, как вы попробуете, не стесняйтесь [отправить нам свой отзыв](https://github.com/facebook/react/issues/new), позитивный или негативный.
-Finally, there is no rush to migrate to Hooks. We recommend avoiding any "big rewrites", especially for existing, complex class components. It takes a bit of a mindshift to start "thinking in Hooks". In our experience, it's best to practice using Hooks in new and non-critical components first, and ensure that everybody on your team feels comfortable with them. After you give Hooks a try, please feel free to [send us feedback](https://github.com/facebook/react/issues/new), positive or negative.
+Мы намерены охватить все возможные варианты использования классов в хуках, но **мы всё ещё будем поддерживать классовые компоненты в обозримом будущем.** В Facebook десятки тысяч компонентов, написанных в виде классов, и у нас нет абсолютно никаких планов их переписывать. Вместо этого мы начинаем использовать хуки в новом коде параллельно с классами.
-We intend for Hooks to cover all existing use cases for classes, but **we will keep supporting class components for the foreseeable future.** At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.
+## Часто задаваемые вопросы {#frequently-asked-questions}
-## Frequently Asked Questions {#frequently-asked-questions}
+Мы подготовили для вас [страницу FAQ](/docs/hooks-faq.html) с ответами на самые частые вопросы о хуках.
-We've prepared a [Hooks FAQ page](/docs/hooks-faq.html) that answers the most common questions about Hooks.
+## Следующие шаги {#next-steps}
-## Next Steps {#next-steps}
-
-By the end of this page, you should have a rough idea of what problems Hooks are solving, but many details are probably unclear. Don't worry! **Let's now go to [the next page](/docs/hooks-overview.html) where we start learning about Hooks by example.**
+К концу этой страницы вы должны иметь общее представление о том, какие проблемы решают хуки, но многие детали, возможно, остались непонятны. Не беспокойтесь! **Давайте перейдём на [следующую страницу](/docs/hooks-overview.html), где мы изучим хуки на примерах.**
diff --git a/content/docs/hooks-overview.md b/content/docs/hooks-overview.md
index fef7de00b..b44635df7 100644
--- a/content/docs/hooks-overview.md
+++ b/content/docs/hooks-overview.md
@@ -1,30 +1,29 @@
---
id: hooks-overview
-title: Hooks at a Glance
+title: Краткий обзор хуков
permalink: docs/hooks-overview.html
next: hooks-state.html
prev: hooks-intro.html
---
-*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
+*Хуки* -- новинка в React 16.8, которая позволяет использовать состояние и другие возможности React без написания классов.
-Hooks are [backwards-compatible](/docs/hooks-intro.html#no-breaking-changes). This page provides an overview of Hooks for experienced React users. This is a fast-paced overview. If you get confused, look for a yellow box like this:
+Хуки -- [обратно-совместимы](/docs/hooks-intro.html#no-breaking-changes). На этой странице вы получите общее представление о хуках. Имейте в виду, что это беглый обзор, который больше подойдет опытным пользователям React. В конце каждого раздела есть вот такой жёлтый блок с детальным объяснением на случай, если вы запутались:
->Detailed Explanation
+>Подробное объяснение
>
->Read the [Motivation](/docs/hooks-intro.html#motivation) to learn why we're introducing Hooks to React.
+>Если вы хотите понять, почему мы добавляем хуки в React, прочтите [мотивацию](/docs/hooks-intro.html#motivation).
-**↑↑↑ Each section ends with a yellow box like this.** They link to detailed explanations.
-## 📌 State Hook {#-state-hook}
+## 📌 Хук состояния {#state-hook}
-This example renders a counter. When you click the button, it increments the value:
+Рассмотрим пример, в котором рендерится счётчик. Если вы нажмёте на кнопку, значение счётчика будет инкрементировано.
```js{1,4,5}
import React, { useState } from 'react';
function Example() {
- // Declare a new state variable, which we'll call "count"
+ // Объявляем новую переменную состояния "count"
const [count, setCount] = useState(0);
return (
@@ -38,17 +37,18 @@ function Example() {
}
```
-Here, `useState` is a *Hook* (we'll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders. `useState` returns a pair: the *current* state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It's similar to `this.setState` in a class, except it doesn't merge the old and new state together. (We'll show an example comparing `useState` to `this.state` in [Using the State Hook](/docs/hooks-state.html).)
+В этом примере, `useState` -- это *хук* (определение хука дано ниже). Мы вызываем его, чтобы наделить наш функциональный компонент внутренним состоянием. React будет хранить это состояние между рендерами. Вызов `useState` возвращает две вещи: *текущее* значение состояния и функцию для его обновления. Эту функцию можно использовать где угодно, например, в обработчике событий. Она схожа с `this.setState` в классах, но не слияет новое и старое состояние вместе. Сравнение хука `useState` и `this.state` приводится на странице [Использование хука состояния](/docs/hooks-state.html).
-The only argument to `useState` is the initial state. In the example above, it is `0` because our counter starts from zero. Note that unlike `this.state`, the state here doesn't have to be an object -- although it can be if you want. The initial state argument is only used during the first render.
+Единственный аргумент `useState` -- это начальное состояние. В примере выше -- это `0`, так как наш счётчик начинается с нуля. Заметьте, что в отличие от `this.state`, в нашем случае состояние может, но не обязано, быть объектом. Исходное значение аргумента используется только при первом рендере.
-#### Declaring multiple state variables {#declaring-multiple-state-variables}
-You can use the State Hook more than once in a single component:
+#### Объявление нескольких переменных состояния {#declaring-multiple-state-variables}
+
+Хук состояния можно использовать в компоненте более одного раза.
```js
function ExampleWithManyStates() {
- // Declare multiple state variables!
+ // Обьявляем несколько переменных состояния!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
@@ -56,25 +56,25 @@ function ExampleWithManyStates() {
}
```
-The [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring) syntax lets us give different names to the state variables we declared by calling `useState`. These names aren't a part of the `useState` API. Instead, React assumes that if you call `useState` many times, you do it in the same order during every render. We'll come back to why this works and when this is useful later.
+Синтаксис [деструктуризации массивов](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#%D0%A0%D0%B0%D0%B7%D0%B1%D0%BE%D1%80_%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%D0%BE%D0%B2) позволяет нам по разному называть переменные состояния, которые мы объявляем при вызове `useState`. Так как имён этих переменных нет в API `useState`, React предполагает, что если вы вызываете `useState` много раз, вы делаете это в одинаковой последовательности при каждом рендере. Мы расскажем, почему это работает и когда это целесообразно, немного позже.
-#### But what is a Hook? {#but-what-is-a-hook}
+#### Что же такое хук? {#but-what-is-a-hook}
-Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes -- they let you use React without classes. (We [don't recommend](/docs/hooks-intro.html#gradual-adoption-strategy) rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)
+Хуки -- это функции, с помощью которых вы можете "подцепиться" к состоянию и методам жизненного цикла React из функциональных компонентов. Хуки не работают внутри классов -- они дают вам возможность использовать React без классов. (Мы [не рекомендуем](/docs/hooks-intro.html#gradual-adoption-strategy) сразу же переписывать существующие компоненты, но при желании, вы можете начать использовать хуки в своих новых компонентах.)
-React provides a few built-in Hooks like `useState`. You can also create your own Hooks to reuse stateful behavior between different components. We'll look at the built-in Hooks first.
+React содержит несколько встроенных хуков, таких как `useState`. Вы также можете создавать собственные хуки, чтобы повторно использовать их в других своих компонентах. Давайте для начала рассмотрим встроенные хуки.
->Detailed Explanation
+>Подробное объяснение
>
->You can learn more about the State Hook on a dedicated page: [Using the State Hook](/docs/hooks-state.html).
+>Вы можете узнать больше на странице [Использование хука состояния](/docs/hooks-state.html).
-## ⚡️ Effect Hook {#️-effect-hook}
+## ⚡️ Хук эффекта {#effect-hook}
-You've likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations "side effects" (or "effects" for short) because they can affect other components and can't be done during rendering.
+Вам скорее всего доводилось ранее запрашивать данные, делать подписки или вручную менять DOM из React-компонента. Мы расцениваем эти операции как "побочные эффекты" (или сокращённо "эффекты"), так как они могут влиять на работу других компонентов и их нельзя выполнить во время рендера.
-The Effect Hook, `useEffect`, adds the ability to perform side effects from a function component. It serves the same purpose as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` in React classes, but unified into a single API. (We'll show examples comparing `useEffect` to these methods in [Using the Effect Hook](/docs/hooks-effect.html).)
+С помощью хука эффекта `useEffect` вы можете выполнять побочные эффекты из функционального компонента. Он выполняет ту же роль, что и `componentDidMount`, `componentDidUpdate` и `componentWillUnmount` в React-классах, объединив их в единый API. Вы можете найти сравнение `useEffect` и этих методов на странице [использование хука эффекта](/docs/hooks-effect.html).
-For example, this component sets the document title after React updates the DOM:
+К примеру, этот компонент устанавливает заголовок документа после того, как React обновляет DOM:
```js{1,6-10}
import React, { useState, useEffect } from 'react';
@@ -82,9 +82,9 @@ import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
- // Similar to componentDidMount and componentDidUpdate:
+ // По принципу componentDidMount и componentDidUpdate:
useEffect(() => {
- // Update the document title using the browser API
+ // Обновляем заголовок документа, используя API браузера
document.title = `You clicked ${count} times`;
});
@@ -99,9 +99,9 @@ function Example() {
}
```
-When you call `useEffect`, you're telling React to run your "effect" function after flushing changes to the DOM. Effects are declared inside the component so they have access to its props and state. By default, React runs the effects after every render -- *including* the first render. (We'll talk more about how this compares to class lifecycles in [Using the Effect Hook](/docs/hooks-effect.html).)
+Когда вы вызываете `useEffect`, React получает указание запустить вашу функцию с "эффектом" после того, как он отправил изменения в DOM. Поскольку эффекты объявляются внутри компонента, у них есть доступ к его пропсам и состоянию. По умолчанию, React запускает эффекты после каждого рендера, *включая* первый рендер. Мы рассмотрим более подробно, как это отличается от классовых методов жизненного цикла на странице [использование хука эффекта](/docs/hooks-effect.html).
-Effects may also optionally specify how to "clean up" after them by returning a function. For example, this component uses an effect to subscribe to a friend's online status, and cleans up by unsubscribing from it:
+При необходимости вы можете вернуть из эффекта функцию, которая указывает эффекту, как выполнить за собой "сброс". Например, этот компонент использует эффект, чтобы подписаться на статус друга в сети, и выполняет сброс, отписываясь от него.
```js{10-16}
import React, { useState, useEffect } from 'react';
@@ -128,9 +128,9 @@ function FriendStatus(props) {
}
```
-In this example, React would unsubscribe from our `ChatAPI` when the component unmounts, as well as before re-running the effect due to a subsequent render. (If you want, there's a way to [tell React to skip re-subscribing](/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects) if the `props.friend.id` we passed to `ChatAPI` didn’t change.)
+В этом примере, React будет отписываться от нашего `ChatAPI` перед тем, как компонент размонтируется и перед тем, как перезапустить эффект при повторном рендере. Вы можете сделать так, чтобы [React пропускал повторные подписки](/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects) если `props.friend.id`, который мы передали в `ChatAPI`, остался без изменений.
-Just like with `useState`, you can use more than a single effect in a component:
+Так же как и `useState`, вы можете использовать более одного эффекта в компоненте:
```js{3,8}
function FriendStatusWithCounter(props) {
@@ -153,32 +153,32 @@ function FriendStatusWithCounter(props) {
// ...
```
-Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.
+Хуки дают вам возможность организовать побочные эффекты в компоненте по связанным частям (например, добавление или отмена подписки), вместо того, чтобы принуждать вас делить все согласно методам жизненного цикла.
->Detailed Explanation
+>Подробное объяснение
>
->You can learn more about `useEffect` on a dedicated page: [Using the Effect Hook](/docs/hooks-effect.html).
+>Вы можете узнать больше о `useEffect` на странице [Использование хука эффекта](/docs/hooks-effect.html).
-## ✌️ Rules of Hooks {#️-rules-of-hooks}
+## ✌️ Правила хуков {#rules-of-hooks}
-Hooks are JavaScript functions, but they impose two additional rules:
+Хуки -- это функции JavaScript, которые налагают два дополнительных правила:
-* Only call Hooks **at the top level**. Don’t call Hooks inside loops, conditions, or nested functions.
-* Only call Hooks **from React function components**. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks -- your own custom Hooks. We'll learn about them in a moment.)
+* Хуки следует вызывать только **на верхнем уровне**. Не вызывайте хуки внутри циклов, условий или вложенных функций.
+* Хуки следует вызывать только **из функциональных компонентов React**. Не вызывайте хуки из обычных JavaScript-функций. Есть только одно исключение, откуда можно вызывать хуки -- это ваши пользовательские хуки. Мы расскажем о них далее.
-We provide a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to enforce these rules automatically. We understand these rules might seem limiting or confusing at first, but they are essential to making Hooks work well.
+Мы разработали специальный [плагин для линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks), который помогает обеспечивать соблюдение этих правил. Мы понимаем, что эти правила могут показаться немного непонятными и накладывать определённые ограничения, но они очень важны для правильной работы хуков.
->Detailed Explanation
+>Подробное объяснение
>
->You can learn more about these rules on a dedicated page: [Rules of Hooks](/docs/hooks-rules.html).
+>Вы можете узнать больше на странице [Правила хуков](/docs/hooks-rules.html).
-## 💡 Building Your Own Hooks {#-building-your-own-hooks}
+## 💡 Создание собственных хуков {#building-your-own-hooks}
-Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: [higher-order components](/docs/higher-order-components.html) and [render props](/docs/render-props.html). Custom Hooks let you do this, but without adding more components to your tree.
+Иногда нужно повторно использовать одинаковую логику состояния в нескольких компонентах. Традиционно использовались подхода: [компоненты высшего порядка](/docs/higher-order-components.html) и [рендер-пропсы](/docs/render-props.html). С помощью пользовательских хуков эта задача решается без добавления ненужных компонентов в ваше дерево.
-Earlier on this page, we introduced a `FriendStatus` component that calls the `useState` and `useEffect` Hooks to subscribe to a friend's online status. Let's say we also want to reuse this subscription logic in another component.
+Ранее на этой странице мы рассматривали компонент `FriendStatus`, который вызывал хуки `useState` и `useEffect`, чтобы подписаться на статус друга в сети. Допустим, мы хотим ещё раз использовать эту логику с подпиской, но уже в другом компоненте.
-First, we'll extract this logic into a custom Hook called `useFriendStatus`:
+Прежде всего, давайте извлечём эту логику в пользовательский хук `useFriendStatus`
```js{3}
import React, { useState, useEffect } from 'react';
@@ -201,9 +201,9 @@ function useFriendStatus(friendID) {
}
```
-It takes `friendID` as an argument, and returns whether our friend is online.
+Хук принимает `friendID` в качестве аргумента и возвращает переменную, которая показывает, в сети наш друг или нет.
-Now we can use it from both components:
+Теперь мы можем использовать этот хук в обоих наших компонентах:
```js{2}
@@ -229,19 +229,19 @@ function FriendListItem(props) {
}
```
-The state of these components is completely independent. Hooks are a way to reuse *stateful logic*, not state itself. In fact, each *call* to a Hook has a completely isolated state -- so you can even use the same custom Hook twice in one component.
+Состояния этих компонентов никаким образом не зависят друг от друга. Хуки -- это способ использовать повторно *логику состояния*, а не само состояние. Более того, каждое *обращение* к хуку обеспечивает совершенно изолированное состояние. Вы даже можете использовать один и тот же хук несколько раз в одном компоненте.
-Custom Hooks are more of a convention than a feature. If a function's name starts with "`use`" and it calls other Hooks, we say it is a custom Hook. The `useSomething` naming convention is how our linter plugin is able to find bugs in the code using Hooks.
+Пользовательские хуки это в большей степени соглашение, чем дополнение. Если имя функции начинается с "`use`" и она вызывает другие хуки, мы расцениваем это как пользовательский хук. Если вы будете придерживаться соглашения `useSomething` при именовании хуков, это позволит нашему плагину для линтера найти баги в коде, который использует хуки.
-You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and probably many more we haven't considered. We are excited to see what custom Hooks the React community will come up with.
+Есть много подходящих случаев, чтобы написать пользовательские хуки, такие как работа с формами, анимация, декларативные подписки, таймеры и, наверное, много других, о которых мы даже не думали. Мы с нетерпением ждём увидеть, какие же пользовательские хуки сообщество React сможет придумать.
->Detailed Explanation
+>Подробное объяснение
>
->You can learn more about custom Hooks on a dedicated page: [Building Your Own Hooks](/docs/hooks-custom.html).
+>Вы можете узнать больше на странице [Создание пользовательских хуков](/docs/hooks-custom.html).
-## 🔌 Other Hooks {#-other-hooks}
+## 🔌 Другие хуки {#other-hooks}
-There are a few less commonly used built-in Hooks that you might find useful. For example, [`useContext`](/docs/hooks-reference.html#usecontext) lets you subscribe to React context without introducing nesting:
+Есть ещё несколько менее используемых встроенных хуков, которые могут вам пригодиться. Например, с помощью [`useContext`](/docs/hooks-reference.html#usecontext), вы можете подписаться на контекст React без использования каких-либо вложений.
```js{2,3}
function Example() {
@@ -251,7 +251,7 @@ function Example() {
}
```
-And [`useReducer`](/docs/hooks-reference.html#usereducer) lets you manage local state of complex components with a reducer:
+А хук [`useReducer`](/docs/hooks-reference.html#usereducer) даёт возможность управлять внтуренним состоянием более сложного компонента с помощью редюсера.
```js{2}
function Todos() {
@@ -259,14 +259,14 @@ function Todos() {
// ...
```
->Detailed Explanation
+>Подробное объяснение
>
->You can learn more about all the built-in Hooks on a dedicated page: [Hooks API Reference](/docs/hooks-reference.html).
+>Вы можете узнать больше обо всех встроенных хуках на странице [справочник API хуков](/docs/hooks-reference.html).
-## Next Steps {#next-steps}
+## Что дальше? {#next-steps}
-Phew, that was fast! If some things didn't quite make sense or you'd like to learn more in detail, you can read the next pages, starting with the [State Hook](/docs/hooks-state.html) documentation.
+Фух, давайте перестанем торопиться и немного охладим пыл! Если вам что-то непонятно или вы хотите узнать о чем-либо более подробно, вы можете начать читать следующие страницы, начиная с документации [хука состояния](/docs/hooks-state.html).
-You can also check out the [Hooks API reference](/docs/hooks-reference.html) and the [Hooks FAQ](/docs/hooks-faq.html).
+Вы также можете просмотреть [справочник API хуков](/docs/hooks-reference.html) и [FAQ хуков](/docs/hooks-faq.html).
-Finally, don't miss the [introduction page](/docs/hooks-intro.html) which explains *why* we're adding Hooks and how we'll start using them side by side with classes -- without rewriting our apps.
+И наконец, не проходите мимо [вступительной страницы](/docs/hooks-intro.html), на которой вы узнаете *почему* мы добавляем хуки и как мы планируем использовать их вместе с классами без необходимости переписывать наши приложения.
diff --git a/content/docs/hooks-reference.md b/content/docs/hooks-reference.md
index dac51b17a..deeef54cf 100644
--- a/content/docs/hooks-reference.md
+++ b/content/docs/hooks-reference.md
@@ -199,7 +199,7 @@ function reducer(state, action) {
}
}
-function Counter({initialCount}) {
+function Counter({initialState}) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
diff --git a/content/docs/hooks-state.md b/content/docs/hooks-state.md
index 052aecb33..272246d00 100644
--- a/content/docs/hooks-state.md
+++ b/content/docs/hooks-state.md
@@ -1,6 +1,6 @@
---
id: hooks-state
-title: Using the State Hook
+title: Использование хука состояния
permalink: docs/hooks-state.html
next: hooks-effect.html
prev: hooks-overview.html
@@ -8,31 +8,31 @@ prev: hooks-overview.html
*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
-The [previous page](/docs/hooks-intro.html) introduced Hooks with this example:
+На [предыдущей странице](/docs/hooks-intro.html) мы познакомились с хуками на этом примере:
```js{4-5}
import React, { useState } from 'react';
function Example() {
- // Declare a new state variable, which we'll call "count"
+ // Объявление новой переменной состояния «count»
const [count, setCount] = useState(0);
return (
-
You clicked {count} times
+
Вы кликнули {count} раз(а)
setCount(count + 1)}>
- Click me
+ Кликни по мне
);
}
```
-We'll start learning about Hooks by comparing this code to an equivalent class example.
+Давайте начнём изучать хуки, сравнив этот код с эквивалентным кодом на основе класса.
-## Equivalent Class Example {#equivalent-class-example}
+## Эквивалентный пример с классом {#equivalent-class-example}
-If you used classes in React before, this code should look familiar:
+Если вы уже пользовались классами в React, то вам знаком такой код:
```js
class Example extends React.Component {
@@ -46,9 +46,9 @@ class Example extends React.Component {
render() {
return (
-
You clicked {this.state.count} times
+
Вы кликнули {this.state.count} раз(а)
this.setState({ count: this.state.count + 1 })}>
- Click me
+ Кликни по мне
);
@@ -56,39 +56,39 @@ class Example extends React.Component {
}
```
-The state starts as `{ count: 0 }`, and we increment `state.count` when the user clicks a button by calling `this.setState()`. We'll use snippets from this class throughout the page.
+Сначала состояние выглядит как `{ count: 0 }`. Каждый раз, когда пользователь кликает, мы увеличиваем `state.count` на единицу, вызывая `this.setState()`. Мы будем использовать фрагменты этого класса на протяжении всей страницы.
->Note
+>Примечание
>
->You might be wondering why we're using a counter here instead of a more realistic example. This is to help us focus on the API while we're still making our first steps with Hooks.
+>Возможно, вы спросите себя, почему мы используем в качестве примера счётчик, а не что-то более реалистичное. Дело в том, что мы хотим обратить ваше внимание на API, одновременно делая первые шаги с хуками.
-## Hooks and Function Components {#hooks-and-function-components}
+## Хуки и функциональные компоненты {#hooks-and-function-components}
-As a reminder, function components in React look like this:
+Напоминаем, что функциональные компоненты в React выглядят так:
```js
const Example = (props) => {
- // You can use Hooks here!
+ // Тут мог бы быть ваш хук!
return
;
}
```
-or this:
+или так:
```js
function Example(props) {
- // You can use Hooks here!
+ // Тут мог бы быть ваш хук!
return
;
}
```
-You might have previously known these as "stateless components". We're now introducing the ability to use React state from these, so we prefer the name "function components".
+Возможно, вы слышали, что такие компоненты называются «компонентами *без* состояния». Сейчас мы покажем, как использовать внутри них состояние React, поэтому будем называть их «функциональными компонентами».
-Hooks **don't** work inside classes. But you can use them instead of writing classes.
+Хуки **НЕ** работают внутри классов, а используются *вместо* них.
-## What's a Hook? {#whats-a-hook}
+## Что такое хук? {#whats-a-hook}
-Our new example starts by importing the `useState` Hook from React:
+Наш новый пример начинается с того, что импортирует хук `useState` из React:
```js{1}
import React, { useState } from 'react';
@@ -98,17 +98,17 @@ function Example() {
}
```
-**What is a Hook?** A Hook is a special function that lets you "hook into" React features. For example, `useState` is a Hook that lets you add React state to function components. We'll learn other Hooks later.
+**Что такое хук?** Хук — это специальная функция, которая позволяет «подцепиться» к возможностям React. Например, хук `useState` предоставляет функциональным компонентам доступ к состоянию React. Мы узнаем про другие хуки чуть позже.
-**When would I use a Hook?** If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We're going to do that right now!
+**Когда применить хук?** Раньше, если вы писали функциональный компонент и осознавали, что вам нужно наделить его состоянием, вам приходилось превращать этот компонент в класс. Теперь же вы можете использовать хук внутри существующего функционального компонента. Мы покажем это прямо сейчас!
->Note:
+>Примечание:
>
->There are some special rules about where you can and can't use Hooks within a component. We'll learn them in [Rules of Hooks](/docs/hooks-rules.html).
+>Есть специальные правила о том, где можно, а где нельзя использовать хуки внутри компонента. Их мы изучим в главе [Правила хуков](/docs/hooks-rules.html).
-## Declaring a State Variable {#declaring-a-state-variable}
+## Объявление переменной состояния {#declaring-a-state-variable}
-In a class, we initialize the `count` state to `0` by setting `this.state` to `{ count: 0 }` in the constructor:
+Допустим, мы хотим инициализировать в классе состояние `count` значением `0`. Для этого в его конструкторе присваиваем `this.state` объект `{ count: 0 }`:
```js{4-6}
class Example extends React.Component {
@@ -120,76 +120,76 @@ class Example extends React.Component {
}
```
-In a function component, we have no `this`, so we can't assign or read `this.state`. Instead, we call the `useState` Hook directly inside our component:
+В функциональном компоненте нам недоступен `this`, поэтому мы не можем задать или считать состояние через `this.state`. Вместо этого мы вызываем хук `useState` напрямую изнутри нашего компонента.
```js{4,5}
import React, { useState } from 'react';
function Example() {
- // Declare a new state variable, which we'll call "count"
+ // Объявление новой переменной состояния «count»
const [count, setCount] = useState(0);
```
-**What does calling `useState` do?** It declares a "state variable". Our variable is called `count` but we could call it anything else, like `banana`. This is a way to "preserve" some values between the function calls — `useState` is a new way to use the exact same capabilities that `this.state` provides in a class. Normally, variables "disappear" when the function exits but state variables are preserved by React.
+**Что делает вызов `useState`?** Он объявляет «переменную состояния». Мы называли переменную `count`, но могли дать ей любое имя, хоть `банан`. Таким образом мы можем «сохранить» некоторые значения между вызовами функции. `useState` это новый способ использовать те же возможности, что даёт `this.state` в классах. Обычно переменные «исчезают» при выходе из функции. К переменным состояния это не относится, потому что их сохраняет React.
-**What do we pass to `useState` as an argument?** The only argument to the `useState()` Hook is the initial state. Unlike with classes, the state doesn't have to be an object. We can keep a number or a string if that's all we need. In our example, we just want a number for how many times the user clicked, so pass `0` as initial state for our variable. (If we wanted to store two different values in state, we would call `useState()` twice.)
+**Какие аргументы передавать `useState`?** Единственный аргумент `useState` это исходное состояние. В отличие от случая с классами, состояние может быть и не объектом, а строкой или числом, если нам так удобно. Поскольку в нашем примере отслеживается количество сделанных пользователем кликов, мы передаём `0` в качестве исходного значения переменной. (Если нам нужно было бы хранить два разных значения в состоянии, то пришлось бы вызвать `useState()` дважды.)
-**What does `useState` return?** It returns a pair of values: the current state and a function that updates it. This is why we write `const [count, setCount] = useState()`. This is similar to `this.state.count` and `this.setState` in a class, except you get them in a pair. If you're not familiar with the syntax we used, we'll come back to it [at the bottom of this page](/docs/hooks-state.html#tip-what-do-square-brackets-mean).
+**Что возвращается из `useState`?** Вызов `useState` вернёт пару значений: текущее состояние и функцию, обновляющую состояние. Поэтому мы пишем `const [count, setCount] = useState()`. Это похоже на `this.state.count` и `this.setState` в классах, с той лишь разницей, что сейчас мы принимаем их сразу в паре. Если вам незнаком использованный синтаксис, мы вернёмся к нему [ближе к концу страницы](/docs/hooks-state.html#tip-what-do-square-brackets-mean).
-Now that we know what the `useState` Hook does, our example should make more sense:
+Теперь мы знаем, что делает `useState`, и пример должен быть ясен:
```js{4,5}
import React, { useState } from 'react';
function Example() {
- // Declare a new state variable, which we'll call "count"
+ // Объявление новой переменной состояния «count»
const [count, setCount] = useState(0);
```
-We declare a state variable called `count`, and set it to `0`. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current `count`, we can call `setCount`.
+Мы объявляем переменную состояния `count` и устанавливаем ей значение `0`. React будет помнить текущее (наиболее свежее) значение между рендерингами и передавать его нашей функции. Если мы захотим изменить `count`, мы вызовем `setCount`.
->Note
+>Примечание
>
->You might be wondering: why is `useState` not named `createState` instead?
+>Может быть, вы спросите себя, почему `useState` не назвали `createState`?
>
->"Create" wouldn't be quite accurate because the state is only created the first time our component renders. During the next renders, `useState` gives us the current state. Otherwise it wouldn't be "state" at all! There's also a reason why Hook names *always* start with `use`. We'll learn why later in the [Rules of Hooks](/docs/hooks-rules.html).
+>Слово «сreate» («создать») было бы не совсем точно, потому что состояние создаётся только в момент, когда компонент рендерится впервые. В последующие же рендеринги `useState` возвращает текущее состояние. Иначе не существовало бы «состояния» как такового. Названия всех хуков начинаются с «use» тоже неспроста. О причине мы узнаем из [Правил хуков](/docs/hooks-rules.html).
-## Reading State {#reading-state}
+## Чтение состояния {#reading-state}
-When we want to display the current count in a class, we read `this.state.count`:
+Когда мы хотим отобразить текущее состояние счётчика в классе, мы обращаемся к `this.state.count`:
```js
- You clicked {this.state.count} times
+ Вы кликнули {this.state.count} раз(а)
```
-In a function, we can use `count` directly:
+В функции же мы можем использовать `count` напрямую:
```js
- You clicked {count} times
+ Вы кликнули {count} раз(а)
```
-## Updating State {#updating-state}
+## Обновление состояния {#updating-state}
-In a class, we need to call `this.setState()` to update the `count` state:
+В классе мы вызываем `this.setState()`, когда надо обновить состояние `count`:
```js{1}
this.setState({ count: this.state.count + 1 })}>
- Click me
+ Кликни по мне
```
-In a function, we already have `setCount` and `count` as variables so we don't need `this`:
+В функции нам не нужен `this`, потому что `setCount` и `count` уже доступны как переменные:
```js{1}
setCount(count + 1)}>
- Click me
+ Кликни по мне
```
-## Recap {#recap}
+## Резюме {#recap}
-Let's now **recap what we learned line by line** and check our understanding.
+Давайте **построчно пробежимся по тому, что мы выучили** и проверим наши знания: