From 867f636797e36995b1bbbc8377b4840ae58773aa Mon Sep 17 00:00:00 2001
From: "translate-react-bot[bot]"
<251169733+translate-react-bot[bot]@users.noreply.github.com>
Date: Thu, 14 May 2026 15:32:39 +0000
Subject: [PATCH 1/4] =?UTF-8?q?docs:=20translate=20`tutorial-tic-tac-toe.m?=
=?UTF-8?q?d`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/content/learn/tutorial-tic-tac-toe.md | 2186 +--------------------
1 file changed, 97 insertions(+), 2089 deletions(-)
diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md
index c80c7f5fe3..7e16cef6cf 100644
--- a/src/content/learn/tutorial-tic-tac-toe.md
+++ b/src/content/learn/tutorial-tic-tac-toe.md
@@ -1,31 +1,31 @@
---
-title: 'Tutorial: Tic-Tac-Toe'
+title: 'Введение: Крестики-нолики'
---
-
+```html
-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. Разархивируйте архив, затем откройте терминал и перейдите в каталог, который вы разархивировали, с помощью команды `cd`
+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 вы увидите три основных раздела:
-
+
-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. Раздел _Files_ со списком файлов, таких как `App.js`, `index.js`, `styles.css` и папка под названием `public`
+1. _Редактор кода_, где вы увидите исходный код выбранного вами файла
+1. Раздел _browser_, где вы увидите, как будет отображаться написанный вами код
-The `App.js` file should be selected in the _Files_ section. The contents of that file in the _code editor_ should be:
+Файл `App.js` должен быть выбран в разделе _Files_. Содержимое этого файла в _редакторе кода_ должно быть:
```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:
+В разделе _browser_ должен отображаться квадрат с буквой X внутри, как здесь:

-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`. Ключевое слово JavaScript `export` делает эту функцию доступной за пределами этого файла. Ключевое слово `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.
+Вторая строка возвращает кнопку. Ключевое слово JavaScript `return` означает, что все, что следует дальше, возвращается как значение вызывающему функцию. `` закрывает 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` в разделе _Files_ 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` в разделе _Files_ 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-фрагмент `<>...>`?
-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:
+Теперь вы должны увидеть:

-Great! Now you just need to copy-paste a few times to add nine squares and...
+Отлично! Теперь вам просто нужно несколько раз скопировать и вставить, чтобы добавить девять квадратов, и...

-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`, у вас есть игровое поле для крестиков-ноликов:

-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`, ваши собственные компоненты `Board` и `Square` должны начинаться с заглавной буквы.
-Let's take a look:
+Давайте посмотрим:

-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:
+Упс, это не то, что вы хотели:

-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:
+Пока что вы должны увидеть пустую доску:

-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:
+Теперь вы снова должны увидеть сетку чисел:

-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` к пропсам элемента button 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!» на вкладке _Console_ в нижней части раздела _Browser_ в 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 `