diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md index c80c7f5fe3..4a0db00251 100644 --- a/src/content/learn/tutorial-tic-tac-toe.md +++ b/src/content/learn/tutorial-tic-tac-toe.md @@ -4,28 +4,28 @@ title: 'Tutorial: Tic-Tac-Toe' -You will build a small tic-tac-toe game during this tutorial. This tutorial does not assume any existing React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React app, and fully understanding it will give you a deep understanding of React. +В этом руководстве вы создадите небольшую игру «крестики-нолики». Это руководство не предполагает предварительных знаний React. Методы, которые вы изучите в ходе руководства, являются основополагающими для создания любого приложения React, и полное их понимание даст вам глубокое представление о React. -This tutorial is designed for people who prefer to **learn by doing** and want to quickly try making something tangible. If you prefer learning each concept step by step, start with [Describing the UI.](/learn/describing-the-ui) +Это руководство предназначено для тех, кто предпочитает **учиться на практике** и хочет быстро попробовать создать что-то осязаемое. Если вы предпочитаете изучать каждую концепцию шаг за шагом, начните с [Описания пользовательского интерфейса.](/learn/describing-the-ui) -The tutorial is divided into several sections: +Руководство разделено на несколько разделов: -- [Setup for the tutorial](#setup-for-the-tutorial) will give you **a starting point** to follow the tutorial. -- [Overview](#overview) will teach you **the fundamentals** of React: components, props, and state. -- [Completing the game](#completing-the-game) will teach you **the most common techniques** in React development. -- [Adding time travel](#adding-time-travel) will give you **a deeper insight** into the unique strengths of React. +- [Настройка для руководства](#setup-for-the-tutorial) предоставит вам **отправную точку** для прохождения руководства. +- [Обзор](#overview) научит вас **основам** React: компонентам, пропсам и состоянию. +- [Завершение игры](#completing-the-game) научит вас **наиболее распространенным методам** в разработке React. +- [Добавление перемотки времени](#adding-time-travel) даст вам **более глубокое понимание** уникальных преимуществ React. -### What are you building? {/*what-are-you-building*/} +### Что вы будете создавать? {/*what-are-you-building*/} -In this tutorial, you'll build an interactive tic-tac-toe game with React. +В этом руководстве вы создадите интерактивную игру «крестики-нолики» с помощью React. -You can see what it will look like when you're finished here: +Вот как она будет выглядеть по завершении: @@ -194,15 +194,15 @@ body { -If the code doesn't make sense to you yet, or if you are unfamiliar with the code's syntax, don't worry! The goal of this tutorial is to help you understand React and its syntax. +Если код пока непонятен или вы не знакомы с синтаксисом кода, не волнуйтесь! Цель этого руководства — помочь вам понять React и его синтаксис. -We recommend that you check out the tic-tac-toe game above before continuing with the tutorial. One of the features that you'll notice is that there is a numbered list to the right of the game's board. This list gives you a history of all of the moves that have occurred in the game, and it is updated as the game progresses. +Мы рекомендуем вам ознакомиться с игрой «крестики-нолики» выше, прежде чем продолжить руководство. Одна из функций, которую вы заметите, — это нумерованный список справа от игрового поля. Этот список содержит историю всех ходов, которые произошли в игре, и обновляется по мере ее продвижения. -Once you've played around with the finished tic-tac-toe game, keep scrolling. You'll start with a simpler template in this tutorial. Our next step is to set you up so that you can start building the game. +После того как вы поиграете с готовой игрой «крестики-нолики», прокрутите дальше. В этом руководстве вы начнете с более простого шаблона. Следующий шаг — подготовить вас к созданию игры. -## Setup for the tutorial {/*setup-for-the-tutorial*/} +## Настройка для руководства {/*setup-for-the-tutorial*/} -In the live code editor below, click **Fork** in the top-right corner to open the editor in a new tab using the website CodeSandbox. CodeSandbox lets you write code in your browser and preview how your users will see the app you've created. The new tab should display an empty square and the starter code for this tutorial. +В редакторе кода ниже нажмите **Fork** в правом верхнем углу, чтобы открыть редактор в новой вкладке с помощью сайта CodeSandbox. CodeSandbox позволяет писать код в браузере и просматривать, как пользователи увидят созданное вами приложение. Новая вкладка должна отображать пустой квадрат и стартовый код для этого руководства. @@ -261,33 +261,33 @@ body { -You can also follow this tutorial using your local development environment. To do this, you need to: +Вы также можете следовать этому руководству, используя свою локальную среду разработки. Для этого вам необходимо: -1. Install [Node.js](https://nodejs.org/en/) -1. In the CodeSandbox tab you opened earlier, press the top-left corner button to open the menu, and then choose **Download Sandbox** in that menu to download an archive of the files locally -1. Unzip the archive, then open a terminal and `cd` to the directory you unzipped -1. Install the dependencies with `npm install` -1. Run `npm start` to start a local server and follow the prompts to view the code running in a browser +1. Установить [Node.js](https://nodejs.org/en/) +1. Во вкладке CodeSandbox, которую вы открыли ранее, нажмите кнопку в верхнем левом углу, чтобы открыть меню, а затем выберите **Download Sandbox** в этом меню, чтобы скачать архив файлов локально +1. Распакуйте архив, затем откройте терминал и перейдите в каталог, который вы распаковали +1. Установите зависимости с помощью `npm install` +1. Запустите `npm start`, чтобы запустить локальный сервер и следовать инструкциям для просмотра кода, работающего в браузере -If you get stuck, don't let this stop you! Follow along online instead and try a local setup again later. +Если вы застряли, не позволяйте этому остановить вас! Вместо этого следуйте онлайн-руководству и попробуйте настроить локальную среду позже. -## Overview {/*overview*/} +## Обзор {/*overview*/} -Now that you're set up, let's get an overview of React! +Теперь, когда вы готовы, давайте получим общее представление о React! -### Inspecting the starter code {/*inspecting-the-starter-code*/} +### Изучение стартового кода {/*inspecting-the-starter-code*/} -In CodeSandbox you'll see three main sections: +В CodeSandbox вы увидите три основных раздела: -![CodeSandbox with starter code](../images/tutorial/react-starter-code-codesandbox.png) +![CodeSandbox со стартовым кодом](../images/tutorial/react-starter-code-codesandbox.png) -1. The _Files_ section with a list of files like `App.js`, `index.js`, `styles.css` and a folder called `public` -1. The _code editor_ where you'll see the source code of your selected file -1. The _browser_ section where you'll see how the code you've written will be displayed +1. Раздел _Файлы_ со списком файлов, таких как `App.js`, `index.js`, `styles.css`, и папкой `public`. +1. _Редактор кода_, где вы увидите исходный код выбранного файла. +1. Раздел _браузер_, где вы увидите, как будет отображаться написанный вами код. -The `App.js` file should be selected in the _Files_ section. The contents of that file in the _code editor_ should be: +Файл `App.js` должен быть выбран в разделе _Файлы_. Содержимое этого файла в _редакторе кода_ должно быть следующим: ```jsx export default function Square() { @@ -295,15 +295,15 @@ export default function Square() { } ``` -The _browser_ section should be displaying a square with an X in it like this: +Раздел _браузер_ должен отображать квадрат с буквой X внутри, как показано здесь: -![x-filled square](../images/tutorial/x-filled-square.png) +![квадрат с X](../images/tutorial/x-filled-square.png) -Now let's have a look at the files in the starter code. +Теперь давайте посмотрим на файлы стартового кода. #### `App.js` {/*appjs*/} -The code in `App.js` creates a _component_. In React, a component is a piece of reusable code that represents a part of a user interface. Components are used to render, manage, and update the UI elements in your application. Let's look at the component line by line to see what's going on: +Код в `App.js` создает _компонент_. В React компонент — это фрагмент многократно используемого кода, представляющий часть пользовательского интерфейса. Компоненты используются для рендеринга, управления и обновления элементов пользовательского интерфейса в вашем приложении. Давайте рассмотрим компонент построчно, чтобы понять, что происходит: ```js {1} export default function Square() { @@ -311,7 +311,7 @@ export default function Square() { } ``` -The first line defines a function called `Square`. The `export` JavaScript keyword makes this function accessible outside of this file. The `default` keyword tells other files using your code that it's the main function in your file. +Первая строка определяет функцию с именем `Square`. Ключевое слово `export` в JavaScript делает эту функцию доступной вне этого файла. Ключевое слово `default` указывает другим файлам, использующим ваш код, что это основная функция в вашем файле. ```js {2} export default function Square() { @@ -319,15 +319,15 @@ export default function Square() { } ``` -The second line returns a button. The `return` JavaScript keyword means whatever comes after is returned as a value to the caller of the function. `` closes the JSX element to indicate that any following content shouldn't be placed inside the button. +Вторая строка возвращает кнопку. Ключевое слово `return` в JavaScript означает, что все, что следует за ним, возвращается в качестве значения вызывающей функции. `` закрывает JSX-элемент, указывая, что любой последующий контент не должен быть помещен внутрь кнопки. #### `styles.css` {/*stylescss*/} -Click on the file labeled `styles.css` in the _Files_ section of CodeSandbox. This file defines the styles for your React app. The first two _CSS selectors_ (`*` and `body`) define the style of large parts of your app while the `.square` selector defines the style of any component where the `className` property is set to `square`. In your code, that would match the button from your Square component in the `App.js` file. +Нажмите на файл с названием `styles.css` в разделе _Файлы_ CodeSandbox. Этот файл определяет стили для вашего React-приложения. Первые два _CSS-селектора_ (`*` и `body`) определяют стиль больших частей вашего приложения, в то время как селектор `.square` определяет стиль любого компонента, у которого свойство `className` установлено в `square`. В вашем коде это будет соответствовать кнопке из вашего компонента Square в файле `App.js`. #### `index.js` {/*indexjs*/} -Click on the file labeled `index.js` in the _Files_ section of CodeSandbox. You won't be editing this file during the tutorial but it is the bridge between the component you created in the `App.js` file and the web browser. +Нажмите на файл с названием `index.js` в разделе _Файлы_ CodeSandbox. Вы не будете редактировать этот файл во время учебника, но он является связующим звеном между компонентом, который вы создали в файле `App.js`, и веб-браузером. ```jsx import { StrictMode } from 'react'; @@ -337,20 +337,20 @@ import './styles.css'; import App from './App'; ``` -Lines 1-5 bring all the necessary pieces together: +Строки 1–5 объединяют все необходимые части: * React -* React's library to talk to web browsers (React DOM) -* the styles for your components -* the component you created in `App.js`. +* Библиотеку React для взаимодействия с веб-браузерами (React DOM) +* Стили для ваших компонентов +* Компонент, который вы создали в `App.js`. -The remainder of the file brings all the pieces together and injects the final product into `index.html` in the `public` folder. +Оставшаяся часть файла объединяет все части и внедряет конечный продукт в `index.html` в папке `public`. -### Building the board {/*building-the-board*/} +### Создание доски {/*building-the-board*/} -Let's get back to `App.js`. This is where you'll spend the rest of the tutorial. +Давайте вернемся к `App.js`. Здесь вы проведете остальную часть учебника. -Currently the board is only a single square, but you need nine! If you just try and copy paste your square to make two squares like this: +В настоящее время доска состоит только из одного квадрата, но вам нужно девять! Если вы просто скопируете и вставите свой квадрат, чтобы создать два квадрата, вот так: ```js {2} export default function Square() { @@ -358,15 +358,15 @@ export default function Square() { } ``` -You'll get this error: +Вы получите эту ошибку: -/src/App.js: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX Fragment `<>...`? +/src/App.js: Смежные JSX-элементы должны быть обернуты в заключающий тег. Вы хотели использовать JSX Fragment `<>...`? -React components need to return a single JSX element and not multiple adjacent JSX elements like two buttons. To fix this you can use *Fragments* (`<>` and ``) to wrap multiple adjacent JSX elements like this: +React-компоненты должны возвращать один JSX-элемент, а не несколько смежных JSX-элементов, таких как две кнопки. Чтобы исправить это, вы можете использовать *Фрагменты* (`<>` и ``) для обертывания нескольких смежных JSX-элементов, вот так: ```js {3-6} export default function Square() { @@ -379,17 +379,17 @@ export default function Square() { } ``` -Now you should see: +Теперь вы должны увидеть: -![two x-filled squares](../images/tutorial/two-x-filled-squares.png) +![два квадрата с X](../images/tutorial/two-x-filled-squares.png) -Great! Now you just need to copy-paste a few times to add nine squares and... +Отлично! Теперь вам просто нужно скопировать и вставить несколько раз, чтобы добавить девять квадратов и... -![nine x-filled squares in a line](../images/tutorial/nine-x-filled-squares.png) +![девять квадратов с X в ряд](../images/tutorial/nine-x-filled-squares.png) -Oh no! The squares are all in a single line, not in a grid like you need for our board. To fix this you'll need to group your squares into rows with `div`s and add some CSS classes. While you're at it, you'll give each square a number to make sure you know where each square is displayed. +О нет! Квадраты расположены в одну линию, а не в сетку, как вам нужно для нашей доски. Чтобы исправить это, вам нужно будет сгруппировать ваши квадраты по строкам с помощью `div` и добавить некоторые CSS-классы. Пока вы этим занимаетесь, вы присвоите каждому квадрату номер, чтобы убедиться, что вы знаете, где отображается каждый квадрат. -In the `App.js` file, update the `Square` component to look like this: +В файле `App.js` обновите компонент `Square`, чтобы он выглядел так: ```js {3-19} export default function Square() { @@ -415,11 +415,11 @@ export default function Square() { } ``` -The CSS defined in `styles.css` styles the divs with the `className` of `board-row`. Now that you've grouped your components into rows with the styled `div`s you have your tic-tac-toe board: +CSS, определенный в `styles.css`, стилизует `div` с `className` `board-row`. Теперь, когда вы сгруппировали свои компоненты по строкам с помощью стилизованных `div`s, у вас есть доска для крестиков-ноликов: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![доска для крестиков-ноликов, заполненная числами от 1 до 9](../images/tutorial/number-filled-board.png) -But you now have a problem. Your component named `Square`, really isn't a square anymore. Let's fix that by changing the name to `Board`: +Но теперь у вас возникла проблема. Ваш компонент с именем `Square` на самом деле больше не является квадратом. Давайте исправим это, изменив имя на `Board`: ```js {1} export default function Board() { @@ -427,7 +427,7 @@ export default function Board() { } ``` -At this point your code should look something like this: +К этому моменту ваш код должен выглядеть примерно так: @@ -504,15 +504,15 @@ body { -Psssst... That's a lot to type! It's okay to copy and paste code from this page. However, if you're up for a little challenge, we recommend only copying code that you've manually typed at least once yourself. +Пссст... Это много для набора! Не страшно копировать и вставлять код с этой страницы. Однако, если вы готовы к небольшому испытанию, мы рекомендуем копировать только тот код, который вы уже набрали вручную хотя бы один раз. -### Passing data through props {/*passing-data-through-props*/} +### Передача данных через пропсы {/*passing-data-through-props*/} -Next, you'll want to change the value of a square from empty to "X" when the user clicks on the square. With how you've built the board so far you would need to copy-paste the code that updates the square nine times (once for each square you have)! Instead of copy-pasting, React's component architecture allows you to create a reusable component to avoid messy, duplicated code. +Далее вы захотите изменить значение квадрата с пустого на "X" при нажатии на квадрат. При текущей структуре доски вам пришлось бы копировать и вставлять код, обновляющий квадрат, девять раз (по одному для каждого квадрата)! Вместо копирования и вставки, архитектура компонентов React позволяет создавать многократно используемый компонент, чтобы избежать беспорядочного, дублирующегося кода. -First, you are going to copy the line defining your first square (``) from your `Board` component into a new `Square` component: +Сначала вы скопируете строку, определяющую ваш первый квадрат (``) из вашего компонента `Board` в новый компонент `Square`: ```js {1-3} function Square() { @@ -524,7 +524,7 @@ export default function Board() { } ``` -Then you'll update the Board component to render that `Square` component using JSX syntax: +Затем вы обновите компонент `Board`, чтобы он рендерил этот компонент `Square` с использованием синтаксиса JSX: ```js {5-19} // ... @@ -551,15 +551,15 @@ export default function Board() { } ``` -Note how unlike the browser `div`s, your own components `Board` and `Square` must start with a capital letter. +Обратите внимание, что в отличие от браузерных `div`s, ваши собственные компоненты `Board` и `Square` должны начинаться с заглавной буквы. -Let's take a look: +Давайте посмотрим: -![one-filled board](../images/tutorial/board-filled-with-ones.png) +![доска, заполненная единицами](../images/tutorial/board-filled-with-ones.png) -Oh no! You lost the numbered squares you had before. Now each square says "1". To fix this, you will use *props* to pass the value each square should have from the parent component (`Board`) to its child (`Square`). +О нет! Вы потеряли пронумерованные квадраты, которые были раньше. Теперь каждый квадрат показывает "1". Чтобы исправить это, вы будете использовать *пропсы* для передачи значения, которое должен иметь каждый квадрат, от родительского компонента (`Board`) к его дочернему (`Square`). -Update the `Square` component to read the `value` prop that you'll pass from the `Board`: +Обновите компонент `Square`, чтобы он считывал проп `value`, который вы будете передавать из `Board`: ```js {1} function Square({ value }) { @@ -567,9 +567,9 @@ function Square({ value }) { } ``` -`function Square({ value })` indicates the Square component can be passed a prop called `value`. +`function Square({ value })` указывает, что компоненту `Square` может быть передан проп с именем `value`. -Now you want to display that `value` instead of `1` inside every square. Try doing it like this: +Теперь вы хотите отобразить этот `value` вместо `1` внутри каждого квадрата. Попробуйте сделать это так: ```js {2} function Square({ value }) { @@ -577,11 +577,11 @@ function Square({ value }) { } ``` -Oops, this is not what you wanted: +Упс, это не то, что вы хотели: -![value-filled board](../images/tutorial/board-filled-with-value.png) +![доска, заполненная словом value](../images/tutorial/board-filled-with-value.png) -You wanted to render the JavaScript variable called `value` from your component, not the word "value". To "escape into JavaScript" from JSX, you need curly braces. Add curly braces around `value` in JSX like so: +Вы хотели отобразить JavaScript-переменную `value` из вашего компонента, а не слово "value". Чтобы "выйти в JavaScript" из JSX, вам нужны фигурные скобки. Добавьте фигурные скобки вокруг `value` в JSX вот так: ```js {2} function Square({ value }) { @@ -589,11 +589,11 @@ function Square({ value }) { } ``` -For now, you should see an empty board: +Пока что вы должны увидеть пустую доску: -![empty board](../images/tutorial/empty-board.png) +![пустая доска](../images/tutorial/empty-board.png) -This is because the `Board` component hasn't passed the `value` prop to each `Square` component it renders yet. To fix it you'll add the `value` prop to each `Square` component rendered by the `Board` component: +Это потому, что компонент `Board` еще не передал проп `value` каждому компоненту `Square`, который он рендерит. Чтобы исправить это, вы добавите проп `value` каждому компоненту `Square`, который рендерит компонент `Board`: ```js {5-7,10-12,15-17} export default function Board() { @@ -619,11 +619,11 @@ export default function Board() { } ``` -Now you should see a grid of numbers again: +Теперь вы снова должны увидеть сетку чисел: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![доска для крестиков-ноликов, заполненная числами от 1 до 9](../images/tutorial/number-filled-board.png) -Your updated code should look like this: +Ваш обновленный код должен выглядеть так: @@ -702,9 +702,9 @@ body { -### Making an interactive component {/*making-an-interactive-component*/} +### Создание интерактивного компонента {/*making-an-interactive-component*/} -Let's fill the `Square` component with an `X` when you click it. Declare a function called `handleClick` inside of the `Square`. Then, add `onClick` to the props of the button JSX element returned from the `Square`: +Давайте заполним компонент `Square` буквой "X" при нажатии. Объявите функцию с именем `handleClick` внутри `Square`. Затем добавьте `onClick` к пропсам JSX-элемента кнопки, возвращаемого из `Square`: ```js {2-4,9} function Square({ value }) { @@ -723,19 +723,19 @@ function Square({ value }) { } ``` -If you click on a square now, you should see a log saying `"clicked!"` in the _Console_ tab at the bottom of the _Browser_ section in CodeSandbox. Clicking the square more than once will log `"clicked!"` again. Repeated console logs with the same message will not create more lines in the console. Instead, you will see an incrementing counter next to your first `"clicked!"` log. +Если вы нажмете на квадрат сейчас, вы увидите в консоли сообщение `"clicked!"` во вкладке _Консоль_ в нижней части раздела _Браузер_ в CodeSandbox. Нажатие на квадрат более одного раза снова выведет `"clicked!"`. Повторяющиеся сообщения в консоли не создадут новых строк в консоли. Вместо этого вы увидите увеличивающийся счетчик рядом с вашим первым сообщением `"clicked!"`. -If you are following this tutorial using your local development environment, you need to open your browser's Console. For example, if you use the Chrome browser, you can view the Console with the keyboard shortcut **Shift + Ctrl + J** (on Windows/Linux) or **Option + ⌘ + J** (on macOS). +Если вы следуете этому учебнику, используя свою локальную среду разработки, вам нужно открыть Консоль вашего браузера. Например, если вы используете браузер Chrome, вы можете просмотреть Консоль с помощью сочетания клавиш **Shift + Ctrl + J** (в Windows/Linux) или **Option + ⌘ + J** (в macOS). -As a next step, you want the Square component to "remember" that it got clicked, and fill it with an "X" mark. To "remember" things, components use *state*. +В качестве следующего шага вы хотите, чтобы компонент `Square` "запомнил", что на него нажали, и заполнил его отметкой "X". Чтобы "запоминать" вещи, компоненты используют *состояние*. -React provides a special function called `useState` that you can call from your component to let it "remember" things. Let's store the current value of the `Square` in state, and change it when the `Square` is clicked. +React предоставляет специальную функцию под названием `useState`, которую вы можете вызвать из своего компонента, чтобы он мог "запоминать" вещи. Давайте сохраним текущее значение `Square` в состоянии и изменим его при нажатии на `Square`. -Import `useState` at the top of the file. Remove the `value` prop from the `Square` component. Instead, add a new line at the start of the `Square` that calls `useState`. Have it return a state variable called `value`: +Импортируйте `useState` в верхней части файла. Удалите проп `value` из компонента `Square`. Вместо этого добавьте новую строку в начале `Square`, которая вызывает `useState`. Пусть она вернет переменную состояния с именем `value`: ```js {1,3,4} import { useState } from 'react'; @@ -747,9 +747,9 @@ function Square() { //... ``` -`value` stores the value and `setValue` is a function that can be used to change the value. The `null` passed to `useState` is used as the initial value for this state variable, so `value` here starts off equal to `null`. +`value` хранит значение, а `setValue` — это функция, которую можно использовать для изменения значения. `null`, переданный в `useState`, используется в качестве начального значения для этой переменной состояния, поэтому `value` здесь изначально равно `null`. -Since the `Square` component no longer accepts props anymore, you'll remove the `value` prop from all nine of the Square components created by the Board component: +Поскольку компонент `Square` больше не принимает пропсы, вы удалите проп `value` из всех девяти компонентов `Square`, созданных компонентом `Board`: ```js {6-8,11-13,16-18} // ... @@ -776,7 +776,7 @@ export default function Board() { } ``` -Now you'll change `Square` to display an "X" when clicked. Replace the `console.log("clicked!");` event handler with `setValue('X');`. Now your `Square` component looks like this: +Теперь вы измените `Square`, чтобы он отображал "X" при нажатии. Замените обработчик события `console.log("clicked!");` на `setValue('X');`. Теперь ваш компонент `Square` выглядит так: ```js {5} function Square() { @@ -797,13 +797,13 @@ function Square() { } ``` -By calling this `set` function from an `onClick` handler, you're telling React to re-render that `Square` whenever its `