diff --git a/content/tutorial/tutorial.md b/content/tutorial/tutorial.md index 1c69ae99f..261b2dc51 100644 --- a/content/tutorial/tutorial.md +++ b/content/tutorial/tutorial.md @@ -1,6 +1,6 @@ --- id: tutorial -title: "Tutorial: Intro to React" +title: "Введение: знакомство с React" layout: tutorial sectionid: tutorial permalink: tutorial/tutorial.html @@ -12,97 +12,99 @@ redirect_from: - "docs/tutorial-zh-CN.html" --- -This tutorial doesn't assume any existing React knowledge. +Вам не обязательно знать React, чтобы проходить это введение. -## Before We Start the Tutorial {#before-we-start-the-tutorial} +## Прежде чем начать {#before-we-start-the-tutorial} -We will build a small game during this tutorial. **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 deep understanding of React. +В этом введении мы будем постепенно создавать небольшую игру. **Возможно, вы захотите пропустить его, потому что не разрабатываете игры, но вам стоит попробовать.** Подходы, которые вы изучите в этом введении, являются основополагающими для создания любого React-приложения. Их освоение даст вам глубокое понимание React. ->Tip +>Совет > ->This tutorial is designed for people who prefer to **learn by doing**. If you prefer learning concepts from the ground up, check out our [step-by-step guide](/docs/hello-world.html). You might find this tutorial and the guide complementary to each other. +>Это введение рассчитано на людей, которые предпочитают **учиться на практике**. Если вам больше нравится изучать предмет от начала до конца, то начните с [пошагового руководства](/docs/hello-world.html). Введение и руководство в чём-то дополняют друг друга. -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. -You don't have to complete all of the sections at once to get the value out of this tutorial. Try to get as far as you can -- even if it's one or two sections. +Вам не обязательно проходить все части сразу, чтобы получить пользу от этого введения. Изучите столько, сколько можете, даже если это будет один или два раздела. -### What Are We Building? {#what-are-we-building} -In this tutorial, we'll show how to build an interactive tic-tac-toe game with React. +### Что мы собираемся писать? {#what-are-we-building} -You can see what we'll be building here: **[Final Result](https://codepen.io/gaearon/pen/gWWZgR?editors=0010)**. If the code doesn't make sense to you, 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 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 is updated as the game progresses. +Результат вы можете посмотреть здесь — **[готовая игра](https://codepen.io/gaearon/pen/gWWZgR?editors=0010)**. Если вы не очень хорошо понимаете код, или вы не знакомы с синтаксисом, не беспокойтесь. Цель этого введения — помочь разобраться с React и его синтаксисом. -You can close the tic-tac-toe game once you're familiar with it. We'll be starting from a simpler template in this tutorial. Our next step is to set you up so that you can start building the game. +Мы советуем вам поиграть в крестики-нолики, прежде чем продолжите чтение. Одна из особенностей, которую вы можете заметить – это нумерованный список справа от игрового поля. Этот список отображает историю всех игровых ходов и обновляется по мере игры. -### Prerequisites {#prerequisites} +Вы можете закрыть игру в крестики-нолики, как только познакомитесь с ней. Мы начнём с простой заготовки. Следующим шагом мы настроим окружение, чтобы вы могли начать создание игры. -We'll assume that you have some familiarity with HTML and JavaScript, but you should be able to follow along even if you're coming from a different programming language. We'll also assume that you're familiar with programming concepts like functions, objects, arrays, and to a lesser extent, classes. -If you need to review JavaScript, we recommend reading [this guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript). Note that we're also using some features from ES6 -- a recent version of JavaScript. In this tutorial, we're using [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) statements. You can use the [Babel REPL](babel://es5-syntax-example) to check what ES6 code compiles to. +### Предварительные требования {#prerequisites} -## Setup for the Tutorial {#setup-for-the-tutorial} +Мы предполагаем, что вы немного знакомы с HTML и JavaScript. Однако, вы сможете изучать введение, даже если знакомы только с другими языками программирования. Мы также полагаем, что вы знакомы с такими понятиями программирования как функции, объекты, массивы и, в меньшей степени, классы. -There are two ways to complete this tutorial: you can either write the code in your browser, or you can set up a local development environment on your computer. +Если вам нужно повторить основы JavaScript, мы рекомендуем прочитать [вот этот учебник](https://developer.mozilla.org/ru/docs/Web/JavaScript/A_re-introduction_to_JavaScript). Обратите внимание, что мы используем некоторые особенности из ES6 (последней версии JavaScript), такие как [стрелочные функции](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [классы](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes), операторы [`let`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/let) и [`const`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/const). Вы можете воспользоваться [Babel REPL](babel://es5-syntax-example), чтобы узнать во что компилируется ES6-код. -### Setup Option 1: Write Code in the Browser {#setup-option-1-write-code-in-the-browser} +## Настройка окружения {#setup-for-the-tutorial} -This is the quickest way to get started! +Есть два варианта прохождения практической части — вы можете писать код в браузере, либо настроить окружение для разработки на компьютере. -First, open this **[Starter Code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010)** in a new tab. The new tab should display an empty tic-tac-toe game board and React code. We will be editing the React code in this tutorial. +### Вариант 1: Пишем код в браузере {#setup-option-1-write-code-in-the-browser} -You can now skip the second setup option, and go to the [Overview](#overview) section to get an overview of React. +Это самый быстрый способ для старта. -### Setup Option 2: Local Development Environment {#setup-option-2-local-development-environment} +Для начала откройте эту **[Заготовку](https://codepen.io/gaearon/pen/oWWQNa?editors=0010)** в новой вкладке. Вы увидите пустое поле для игры в крестики-нолики и код на React, который мы будем постепенно изменять. -This is completely optional and not required for this tutorial! +Можете пропустить следующую чаcть и перейти к [Обзору](#overview) React. + +### Вариант 2: Локальное окружение для разработки {#setup-option-2-local-development-environment} + +Это не является обязательным и не требуется этим вводным руководством!
-Optional: Instructions for following along locally using your preferred text editor +Опционально: Инструкции для написания кода в вашем любимом редакторе -This setup requires more work but allows you to complete the tutorial using an editor of your choice. Here are the steps to follow: +Эти настройки потребуют больше работы, но позволят продолжить разработку с использованием вашего любимого редактора. Вот что нужно сделать: -1. Make sure you have a recent version of [Node.js](https://nodejs.org/en/) installed. -2. Follow the [installation instructions for Create React App](/docs/create-a-new-react-app.html#create-react-app) to make a new project. +1. Убедиться, что у вас установлена последняя версия [Node.js](https://nodejs.org/en/). +2. Выполнить [инструкции по установке Create React App](/docs/create-a-new-react-app.html#create-react-app) для создания нового проекта. ```bash npx create-react-app my-app ``` -3. Delete all files in the `src/` folder of the new project +3. Удалить все файлы в папке `src/` нового проекта. -> Note: +> Примечание: > ->**Don't delete the entire `src` folder, just the original source files inside it.** We'll replace the default source files with examples for this project in the next step. +>**Не удаляйте саму папку `src`, только файлы внутри неё.** Следующим шагом мы заменим стандартные файлы нашими примерами. ```bash cd my-app cd src -# If you're using a Mac or Linux: +# Для пользователей Mac или Linux: rm -f * -# Or, if you're on Windows: +# Для пользователей Windows del * -# Then, switch back to the project folder +# Затем вернёмся в папку проекта cd .. ``` -4. Add a file named `index.css` in the `src/` folder with [this CSS code](https://codepen.io/gaearon/pen/oWWQNa?editors=0100). +4. Создайте файл с именем `index.css` в папке `src/` и добавьте в него [вот этот CSS код](https://codepen.io/gaearon/pen/oWWQNa?editors=0100). -5. Add a file named `index.js` in the `src/` folder with [this JS code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010). +5. Создайте файл с именем `index.js` в папке `src/` и добавьте в него [этот JS код](https://codepen.io/gaearon/pen/oWWQNa?editors=0010). -6. Add these three lines to the top of `index.js` in the `src/` folder: +6. В начало файла `index.js` в папке`src/` добавьте следующие три строчки: ```js import React from 'react'; @@ -110,32 +112,31 @@ import ReactDOM from 'react-dom'; import './index.css'; ``` -Now if you run `npm start` in the project folder and open `http://localhost:3000` in the browser, you should see an empty tic-tac-toe field. - -We recommend following [these instructions](https://babeljs.io/docs/editors/) to configure syntax highlighting for your editor. +Теперь, когда вы запустите `npm start` в папке проекта и откроете `http://localhost:3000` в браузере, вы должны увидеть пустое поле для крестиков-ноликов. +Мы рекомендуем выполнить [эти инструкции](https://babeljs.io/docs/editors/) для настройки подсветки синтаксиса в вашем редакторе.
-### Help, I'm Stuck! {#help-im-stuck} +### Помогите, я застрял! {#help-im-stuck} -If you get stuck, check out the [community support resources](/community/support.html). In particular, [Reactiflux Chat](https://discord.gg/0ZcbPKXt5bZjGY5n) is a great way to get help quickly. If you don't receive an answer, or if you remain stuck, please file an issue, and we'll help you out. +Если вы застряли – обратитесь к [сообществу](/community/support.html). В частности [Чат Reactiflux](https://discord.gg/0ZcbPKXt5bZjGY5n) – это прекрасное место, где вам помогут. Если вы не дождались ответа или всё ещё не решили своей проблемы, пожалуйста, [задайте вопрос](https://github.com/reactjs/ru.reactjs.org/issues/new) и мы вам поможем. -## Overview {#overview} +## Обзор {#overview} -Now that you're set up, let's get an overview of React! +Теперь, когда вы готовы, перейдём к рассмотрению React! -### What Is React? {#what-is-react} +### Что такое React? {#what-is-react} -React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called "components". +React – это декларативная, эффективная и гибкая JavaScript библиотека для создания пользовательских интерфейсов. Она позволяет вам собирать сложный UI из маленьких изолированных кусочков кода, называемых «компонентами». -React has a few different kinds of components, but we'll start with `React.Component` subclasses: +React имеет несколько разных видов компонентов, но мы начнём с подклассов `React.Component`: ```javascript class ShoppingList extends React.Component { render() { return (
-

Shopping List for {this.props.name}

+

Список покупок для {this.props.name}