diff --git a/src/content/learn/index.md b/src/content/learn/index.md
index b57655bc4..d1d8f83de 100644
--- a/src/content/learn/index.md
+++ b/src/content/learn/index.md
@@ -4,51 +4,51 @@ title: Quick Start
-Welcome to the React documentation! This page will give you an introduction to the 80% of React concepts that you will use on a daily basis.
+Добро пожаловать в документацию React! Эта страница познакомит вас с большинством концепций React, которыми вы будете пользоваться каждый день.
-- How to create and nest components
-- How to add markup and styles
-- How to display data
-- How to render conditions and lists
-- How to respond to events and update the screen
-- How to share data between components
+- Как создавать и вкладывать компоненты
+- Как добавлять разметку и стили
+- Как отображать данные
+- Как отрисовывать условия и списки
+- Как реагировать на события и обновлять страницу
+- Как обмениваться данными между компонентами
-## Creating and nesting components {/*components*/}
+## Создание и вложение компонентов {/*components*/}
-React apps are made out of *components*. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
+Приложения на React собираются из *компонентов*. Компонент — это часть пользовательского интерфейса, у которого есть собственная логика и внешность. Компонент может быть маленьким, как кнопка, или большим, как целая страница.
-React components are JavaScript functions that return markup:
+React-компоненты — это функции JavaScript, которые возвращают разметку:
```js
function MyButton() {
return (
-
+
);
}
```
-Now that you've declared `MyButton`, you can nest it into another component:
+Вы объявили компонент `MyButton`, который можно вложить в другой компонент:
```js {5}
export default function MyApp() {
return (
-
Welcome to my app
+
Добро пожаловать в моё приложение
);
}
```
-Notice that `` starts with a capital letter. That's how you know it's a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.
+Обратите внимание на то, что `` начинается с заглавной буквы. Это отличительная черта компонентов React. Названия компонентов в React всегда должны начинаться с заглавной буквы, а теги HTML — с маленькой.
-Have a look at the result:
+Посмотрите на результат:
@@ -56,7 +56,7 @@ Have a look at the result:
function MyButton() {
return (
);
}
@@ -64,7 +64,7 @@ function MyButton() {
export default function MyApp() {
return (
-
Welcome to my app
+
Добро пожаловать в моё приложение
);
@@ -73,49 +73,49 @@ export default function MyApp() {
-The `export default` keywords specify the main component in the file. If you're not familiar with some piece of JavaScript syntax, [MDN](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) and [javascript.info](https://javascript.info/import-export) have great references.
+Ключевые слова `export default` указывают на основной компонент в файле. Для того, чтобы понять некоторые особенности синтаксиса JavaScript, можно пользоваться ресурсами [MDN](https://developer.mozilla.org/ru-RU/docs/web/javascript/reference/statements/export) и [learn.javascript.ru](https://learn.javascript.ru/import-export).
-## Writing markup with JSX {/*writing-markup-with-jsx*/}
+## Написание разметки с JSX {/*writing-markup-with-jsx*/}
-The markup syntax you've seen above is called *JSX*. It is optional, but most React projects use JSX for its convenience. All of the [tools we recommend for local development](/learn/installation) support JSX out of the box.
+Синтаксис разметки, который вы видели выше, называется *JSX*. Он не обязателен, но большинство проектов на React предпочитают его использовать из-за удобства. Все [инструменты, которые мы рекомендуем для локальной разработки,](/learn/installation) поддерживают JSX.
-JSX is stricter than HTML. You have to close tags like ` `. Your component also can't return multiple JSX tags. You have to wrap them into a shared parent, like a `
...
` or an empty `<>...>` wrapper:
+JSX строже HTML. Вам нужно закрывать теги вроде ` `. Ваш компонент также не может возвращать несколько JSX-тегов. Их нужно будет обернуть внутрь общего родителя, например, `
...
` или пустую обёртку вида `<>...>`:
```js {3,6}
function AboutPage() {
return (
<>
-
About
-
Hello there. How do you do?
+
Обо мне
+
Привет. Как дела?
>
);
}
```
-If you have a lot of HTML to port to JSX, you can use an [online converter.](https://transform.tools/html-to-jsx)
+Для того, чтобы перевести большое количество HTML-верстки в JSX, можно использовать [онлайн-конвертер.](https://transform.tools/html-to-jsx)
-## Adding styles {/*adding-styles*/}
+## Добавление стилей {/*adding-styles*/}
-In React, you specify a CSS class with `className`. It works the same way as the HTML [`class`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class) attribute:
+В React CSS-классы объявляются с помощью `className`. Оно работает аналогично HTML-атрибуту [`class`](https://developer.mozilla.org/ru-RU/docs/Web/HTML/Global_attributes/class):
```js
```
-Then you write the CSS rules for it in a separate CSS file:
+В отдельном CSS-файле вы пишете для него CSS-правила:
```css
-/* In your CSS */
+/* В вашем CSS */
.avatar {
border-radius: 50%;
}
```
-React does not prescribe how you add CSS files. In the simplest case, you'll add a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.
+React не ограничивает вас в том, как добавлять CSS-файлы. В самом простом случае вы добавите тег [``](https://developer.mozilla.org/ru-RU/docs/Web/HTML/Element/link) в ваш HTML-файл. Если вы используете инструмент для сборки или фреймворк, обратитесь к его документации, чтобы понять, как добавить CSS-файл в ваш проект.
-## Displaying data {/*displaying-data*/}
+## Отображение данных {/*displaying-data*/}
-JSX lets you put markup into JavaScript. Curly braces let you "escape back" into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display `user.name`:
+Фигурные скобки внутри JSX-разметки позволяют использовать JavaScript, например, для того, чтобы отобразить свою переменную пользователю. Код ниже отобразит `user.name`:
```js {3}
return (
@@ -125,7 +125,7 @@ return (
);
```
-You can also "escape into JavaScript" from JSX attributes, but you have to use curly braces *instead of* quotes. For example, `className="avatar"` passes the `"avatar"` string as the CSS class, but `src={user.imageUrl}` reads the JavaScript `user.imageUrl` variable value, and then passes that value as the `src` attribute:
+Вы также можете использовать JavaScript в атрибутах JSX. В таком случае вам нужно поставить фигурные скобки *вместо* кавычек. Например, `className="avatar"` передаёт строку `"avatar"` как CSS-класс, а `src={user.imageUrl}` считывает значение JavaScript-переменной `user.imageUrl` и передаёт его в качестве атрибута `src`:
```js {3,4}
return (
@@ -136,7 +136,7 @@ return (
);
```
-You can put more complex expressions inside the JSX curly braces too, for example, [string concatenation](https://javascript.info/operators#string-concatenation-with-binary):
+Вы также можете использовать в JSX более сложные выражения внутри фигурных скобок, например, [сложение строк](https://learn.javascript.ru/operators#slozhenie-strok-pri-pomoschi-binarnogo):
@@ -154,7 +154,7 @@ export default function Profile() {
-In the above example, `style={{}}` is not a special syntax, but a regular `{}` object inside the `style={ }` JSX curly braces. You can use the `style` attribute when your styles depend on JavaScript variables.
+В этом примере `style={{}}` не является специальным синтаксисом, а представляет из себя обычный объект `{}` внутри фигурных скобок JSX `style={ }`. Вы можете использовать атрибут `style` в случаях, когда ваши стили зависят от переменных JavaScript.
-## Conditional rendering {/*conditional-rendering*/}
+## Условный рендеринг {/*conditional-rendering*/}
-In React, there is no special syntax for writing conditions. Instead, you'll use the same techniques as you use when writing regular JavaScript code. For example, you can use an [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statement to conditionally include JSX:
+В React не существует специального синтаксиса для описания условий, вместо этого можно использовать обычный код на JavaScript. Например, для условного рендеринга JSX-кода можно применять [`if`](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Statements/if...else):
```js
let content;
@@ -197,7 +197,7 @@ return (
);
```
-If you prefer more compact code, you can use the [conditional `?` operator.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) Unlike `if`, it works inside JSX:
+Если вы предпочитаете писать более компактный код, используйте [условный оператор `?`.](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) В отличие от `if` его можно использовать в JSX:
```js
@@ -209,7 +209,7 @@ If you prefer more compact code, you can use the [conditional `?` operator.](htt
```
-When you don't need the `else` branch, you can also use a shorter [logical `&&` syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#short-circuit_evaluation):
+Когда вам не нужна ветка `else`, можно использовать более короткий [логический оператор `&&`](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Operators/Logical_AND#short-circuit_evaluation):
```js
@@ -217,23 +217,23 @@ When you don't need the `else` branch, you can also use a shorter [logical `&&`
```
-All of these approaches also work for conditionally specifying attributes. If you're unfamiliar with some of this JavaScript syntax, you can start by always using `if...else`.
+Все эти способы подходят и для задания условий в атрибутах. Если вам не знакомы такие синтаксические конструкции JavaScript, вы можете начать с использования `if...else`.
-## Rendering lists {/*rendering-lists*/}
+## Рендеринг списков {/*rendering-lists*/}
-You will rely on JavaScript features like [`for` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) and the [array `map()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to render lists of components.
+Для отрисовки списков компонентов вам будет нужно использовать такие возможности JavaScript, как [цикл `for`](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Statements/for) и [функция массива `map()`](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
-For example, let's say you have an array of products:
+Например, представим, что у вас есть массив продуктов:
```js
const products = [
- { title: 'Cabbage', id: 1 },
- { title: 'Garlic', id: 2 },
- { title: 'Apple', id: 3 },
+ { title: 'Капуста', id: 1 },
+ { title: 'Чеснок', id: 2 },
+ { title: 'Яблоко', id: 3 },
];
```
-Inside your component, use the `map()` function to transform an array of products into an array of `
` items:
+Преобразуйте этот массив в массив элементов `
` с помощью функции `map()` внутри вашего компонента:
```js
const listItems = products.map(product =>
@@ -247,15 +247,15 @@ return (
);
```
-Notice how `
` has a `key` attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items.
+Обратите внимание, что у `
` есть атрибут `key`. Для каждого элемента списка вам нужно задавать ключ в виде строки или числа, который позволит однозначно отделить этот элемент от остальных в списке. Обычно этот ключ берется из ваших данных, например, это может быть идентификатор из базы данных. React использует эти ключи при добавлении, удалении или изменении порядка элементов.
```js
const products = [
- { title: 'Cabbage', isFruit: false, id: 1 },
- { title: 'Garlic', isFruit: false, id: 2 },
- { title: 'Apple', isFruit: true, id: 3 },
+ { title: 'Капуста', isFruit: false, id: 1 },
+ { title: 'Чеснок', isFruit: false, id: 2 },
+ { title: 'Яблоко', isFruit: true, id: 3 },
];
export default function ShoppingList() {
@@ -278,14 +278,14 @@ export default function ShoppingList() {
-## Responding to events {/*responding-to-events*/}
+## Обработка событий {/*responding-to-events*/}
-You can respond to events by declaring *event handler* functions inside your components:
+Вы можете реагировать на события, объявляя внутри ваших компонентов функции *обработчиков событий*:
```js {2-4,7}
function MyButton() {
function handleClick() {
- alert('You clicked me!');
+ alert('Вы нажали на меня!');
}
return (
@@ -296,19 +296,19 @@ function MyButton() {
}
```
-Notice how `onClick={handleClick}` has no parentheses at the end! Do not _call_ the event handler function: you only need to *pass it down*. React will call your event handler when the user clicks the button.
+Заметьте: у `onClick={handleClick}` нет скобок в конце! Не _вызывайте_ функцию обработчика событий: вам нужно просто её *передать*. React вызовет ваш обработчик событий, когда пользователь кликнет по кнопке.
-## Updating the screen {/*updating-the-screen*/}
+## Обновление экрана {/*updating-the-screen*/}
-Often, you'll want your component to "remember" some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add *state* to your component.
+Вам может понадобиться, чтобы компонент «помнил» какую-то информацию и отображал её. Например, вы хотите посчитать сколько раз была нажата кнопка. Для этого добавьте *состояние* в ваш компонент.
-First, import [`useState`](/reference/react/useState) from React:
+Сначала импортируйте [`useState`](/reference/react/useState) из React:
```js
import { useState } from 'react';
```
-Now you can declare a *state variable* inside your component:
+Теперь можно объявить *переменную состояния* внутри вашего компонента:
```js
function MyButton() {
@@ -316,9 +316,9 @@ function MyButton() {
// ...
```
-You’ll get two things from `useState`: the current state (`count`), and the function that lets you update it (`setCount`). You can give them any names, but the convention is to write `[something, setSomething]`.
+`useState` вернет вам две вещи: текущее состояние (`count`) и функцию (`setCount`), которая обновляет его. Можно именовать их как вам угодно, но такого рода вещи принято называть `[something, setSomething]`.
-The first time the button is displayed, `count` will be `0` because you passed `0` to `useState()`. When you want to change state, call `setCount()` and pass the new value to it. Clicking this button will increment the counter:
+При первом показе кнопка `count` будет иметь значение `0`, потому что вы передали `0` в `useState()`. Для изменения состояния вызовите `setCount()` и передайте туда новое значение. Клик на эту кнопку будет увеличивать счётчик:
```js {5}
function MyButton() {
@@ -330,15 +330,15 @@ function MyButton() {
return (
);
}
```
-React will call your component function again. This time, `count` will be `1`. Then it will be `2`. And so on.
+React снова вызовет функцию вашего компонента. На этот раз `count` будет равно `1`, затем `2`, и так далее.
-If you render the same component multiple times, each will get its own state. Click each button separately:
+Если вы рендерите один и тот же компонент несколько раз, то у каждого из них будет своё состояние. Попробуйте покликать на каждую кнопку по отдельности:
@@ -348,7 +348,7 @@ import { useState } from 'react';
export default function MyApp() {
return (
-
Counters that update separately
+
Независимо обновляющиеся счётчики
@@ -364,7 +364,7 @@ function MyButton() {
return (
);
}
@@ -379,59 +379,59 @@ button {
-Notice how each button "remembers" its own `count` state and doesn't affect other buttons.
+Обратите внимание на то, как каждая кнопка "помнит" свое состояние `count` и не влияет на другие кнопки.
-## Using Hooks {/*using-hooks*/}
+## Использование хуков {/*using-hooks*/}
-Functions starting with `use` are called *Hooks*. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [API reference.](/reference/react) You can also write your own Hooks by combining the existing ones.
+Функции, которые начинаются с `use`, называются *хуками*. `useState` — это встроенный хук в React. В [справочнике API](/reference/react) приводятся другие встроенные хуки. Также, вы можете писать свои собственные хуки, совмещая их с уже существующими.
-Hooks are more restrictive than other functions. You can only call Hooks *at the top* of your components (or other Hooks). If you want to use `useState` in a condition or a loop, extract a new component and put it there.
+У хуков больше ограничений, чем у других функций. Хуки могут вызываться только *в начале* ваших компонентов (или других хуков). Если вам нужен `useState` в условии или цикле, выделите новый компонент и используйте его там.
-## Sharing data between components {/*sharing-data-between-components*/}
+## Обмен данными между компонентами {/*sharing-data-between-components*/}
-In the previous example, each `MyButton` had its own independent `count`, and when each button was clicked, only the `count` for the button clicked changed:
+В предыдущем примере у каждого `MyButton` имеется своё собственное состояние `count`, и при клике на каждую кнопку обновление `count` происходило только у нажатой кнопки.
-
+
-Initially, each `MyButton`'s `count` state is `0`
+В начале у каждого `MyButton` состояние `count` равно `0`
-
+
-The first `MyButton` updates its `count` to `1`
+Первый компонент `MyButton` обновляет свой `count` значением `1`
-However, often you'll need components to *share data and always update together*.
+Однако, вы будете часто сталкиваться с ситуацией, когда вам будет нужно, чтобы компоненты *имели общие данные и всегда обновлялись вместе*.
-To make both `MyButton` components display the same `count` and update together, you need to move the state from the individual buttons "upwards" to the closest component containing all of them.
+Для того, чтобы оба компонента `MyButton` отображали одно и то же значение `count`, вам нужно перенести состояние из отдельных кнопок «выше», в ближайший компонент, содержащий эти компоненты.
-In this example, it is `MyApp`:
+В этом случае таким компонентом является `MyApp`:
-
+
-Initially, `MyApp`'s `count` state is `0` and is passed down to both children
+Сначала состояние `count` компонента `MyApp` равно `0` и передаётся обоим потомкам
-
+
-On click, `MyApp` updates its `count` state to `1` and passes it down to both children
+При клике `MyApp` обновляет своё состояние `count` на значение `1` и передаёт его вниз обоим потомкам
-Now when you click either button, the `count` in `MyApp` will change, which will change both of the counts in `MyButton`. Here's how you can express this in code.
+Теперь, когда вы нажимаете на любую из кнопок, `count` в `MyApp` будет менять своё значение, что в свою очередь повлечёт обновление счётчиков в обоих компонентах `MyButton`. Вот как это можно выразить в коде.
-First, *move the state up* from `MyButton` into `MyApp`:
+Сначала *переместите вверх состояние* из `MyButton` в `MyApp`:
```js {2-6,18}
export default function MyApp() {
@@ -443,7 +443,7 @@ export default function MyApp() {
return (
-
Counters that update separately
+
Независимо обновляющиеся счётчики
@@ -451,12 +451,12 @@ export default function MyApp() {
}
function MyButton() {
- // ... we're moving code from here ...
+ // ... мы перемещаем код отсюда ...
}
```
-Then, *pass the state down* from `MyApp` to each `MyButton`, together with the shared click handler. You can pass information to `MyButton` using the JSX curly braces, just like you previously did with built-in tags like ``:
+Затем *передайте состояние на уровень ниже* из `MyApp` каждому `MyButton` вместе с общим обработчиком клика. Можно передавать информацию в `MyButton` через фигурные скобки JSX таким же образом, как вы это делали со встроенными тегами наподобие ``:
```js {11-12}
export default function MyApp() {
@@ -468,7 +468,7 @@ export default function MyApp() {
return (
-
Counters that update together
+
Одновременно обновляющиеся счётчики
@@ -476,21 +476,21 @@ export default function MyApp() {
}
```
-The information you pass down like this is called _props_. Now the `MyApp` component contains the `count` state and the `handleClick` event handler, and *passes both of them down as props* to each of the buttons.
+Информация, которую вы передаёте таким образом, называется _пропсами_. Теперь у компонента `MyApp` есть состояние `count` и обработчик событий `handleClick`, *которые он передаёт в качестве пропсов* каждой кнопке-потомку.
-Finally, change `MyButton` to *read* the props you have passed from its parent component:
+Наконец, измените компонент `MyButton` так, чтобы он *считывал* пропсы, переданные от своего родителя:
```js {1,3}
function MyButton({ count, onClick }) {
return (
);
}
```
-When you click the button, the `onClick` handler fires. Each button's `onClick` prop was set to the `handleClick` function inside `MyApp`, so the code inside of it runs. That code calls `setCount(count + 1)`, incrementing the `count` state variable. The new `count` value is passed as a prop to each button, so they all show the new value. This is called "lifting state up". By moving state up, you've shared it between components.
+При нажатии на кнопку срабатывает обработчик `onClick`. Каждой кнопке в качестве значения пропа `onClick` задана функция `handleClick` из `MyApp`, поэтому выполняется соответствующий код. Этот код вызывает функцию `setCount(count + 1)`, увеличивая значение состояния `count`. Новое значение `count` передаётся каждой кнопке в качестве пропа, поэтому они все отображают новое значение. Это называется "подъёмом состояния вверх". Поднимая состояние вверх, вы делаете его общим для всех компонентов.
@@ -531,8 +531,8 @@ button {
-## Next Steps {/*next-steps*/}
+## Следующие шаги {/*next-steps*/}
-By now, you know the basics of how to write React code!
+Теперь вы знаете основы того, как писать код для React!
-Check out the [Tutorial](/learn/tutorial-tic-tac-toe) to put them into practice and build your first mini-app with React.
+Ознакомьтесь с [введением](/learn/tutorial-tic-tac-toe), в рамках которого вы сможете применить полученные знания и собрать своё первое мини-приложение на React.