diff --git a/src/content/learn/your-first-component.md b/src/content/learn/your-first-component.md index 343823aa4..f4b58b216 100644 --- a/src/content/learn/your-first-component.md +++ b/src/content/learn/your-first-component.md @@ -1,47 +1,47 @@ --- -title: Your First Component +title: Ваш первый компонент --- -*Components* are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI), which makes them the perfect place to start your React journey! +*Компоненты* — это один из основных концептов React. Они являются основой, на которой вы строите пользовательские интерфейсы (UI), что делает их идеальным местом для начала вашего пути в React! -* What a component is -* What role components play in a React application -* How to write your first React component +* Что такое компонент +* Какую роль играют компоненты в React-приложении +* Как написать ваш первый React-компонент -## Components: UI building blocks {/*components-ui-building-blocks*/} +## Компоненты: строительные блоки UI {/*components-ui-building-blocks*/} -On the Web, HTML lets us create rich structured documents with its built-in set of tags like `

` and `
  • `: +В интернете HTML позволяет создавать нам структурированные документы, используя встроенный набор тегов, например `

    ` и `
  • `: ```html
    -

    My First Component

    +

    Мой первый компонент

      -
    1. Components: UI Building Blocks
    2. -
    3. Defining a Component
    4. -
    5. Using a Component
    6. +
    7. Компоненты: строительные блоки UI
    8. +
    9. Определение компонента
    10. +
    11. Использование компонента
    ``` -This markup represents this article `
    `, its heading `

    `, and an (abbreviated) table of contents as an ordered list `
      `. Markup like this, combined with CSS for style, and JavaScript for interactivity, lies behind every sidebar, avatar, modal, dropdown—every piece of UI you see on the Web. +Разметка выше представляет эту статью как `
      `, её заголовок как `

      ` и (сокращённое) оглавление как упорядоченный список `
        `. Такая разметка, в сочетании с CSS для стилизации и JavaScript для создания интерактивности, кроется в каждой боковой панели, аватаре, модальном окне, выпадающем меню — каждой части UI, которую вы видите в интернете. -React lets you combine your markup, CSS, and JavaScript into custom "components", **reusable UI elements for your app.** The table of contents code you saw above could be turned into a `` component you could render on every page. Under the hood, it still uses the same HTML tags like `
        `, `

        `, etc. +С React можно объединять разметку, CSS и JavaScript в ваши собственные "компоненты", **переиспользуемые элементы UI для вашего приложения**. Код оглавления выше, можно превратить в компонент `` и отрендерить его на любой странице. Внутри он всё ещё использует те же HTML-теги, такие как `
        `, `

        ` и т.д. -Just like with HTML tags, you can compose, order and nest components to design whole pages. For example, the documentation page you're reading is made out of React components: +Как и HTML-теги, компоненты можно комбинировать, упорядочивать и вкладывать друг в друга для создания целых страниц. Например, страница документации, которую вы сейчас читаете, состоит из React-компонентов: ```js - Docs + Документация @@ -51,11 +51,11 @@ Just like with HTML tags, you can compose, order and nest components to design w ``` -As your project grows, you will notice that many of your designs can be composed by reusing components you already wrote, speeding up your development. Our table of contents above could be added to any screen with ``! You can even jumpstart your project with the thousands of components shared by the React open source community like [Chakra UI](https://chakra-ui.com/) and [Material UI.](https://material-ui.com/) +По мере роста вашего проекта вы заметите, что многие из ваших дизайнов можно создать, переиспользуя уже готовые компоненты, а это ускорит разработку. Наше оглавление выше может быть добавлено на любой экран как ``! Можно дать резкий старт своему проекту, используя тысячи компонентов с открытым исходным кодом, которые были созданы React-сообществом, например [Chakra UI](https://chakra-ui.com/) и [Material UI.](https://material-ui.com/) -## Defining a component {/*defining-a-component*/} +## Определение компонента {/*defining-a-component*/} -Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: **a React component is a JavaScript function that you can _sprinkle with markup_.** Here's what that looks like (you can edit the example below): +Раньше при создании веб-страниц разработчики размечали свой контент, а затем добавляли щепотку интерактивности с помощью JavaScript. Это работало отлично, ведь интерактивность в интернете была просто приятной мелочью. Сегодня же это обязательная часть многих сайтов, еще больше — приложений. React ставит интерактивность на первое место, при этом используя ту же технологию: **React-компонент представляет собой JavaScript-функцию, которую можно _припудрить разметкой_.** Вот как это выглядит (вы можете редактировать пример ниже): @@ -64,7 +64,7 @@ export default function Profile() { return ( Katherine Johnson ) } @@ -76,51 +76,51 @@ img { height: 200px; } -And here's how to build a component: +А вот как создать компонент: -### Step 1: Export the component {/*step-1-export-the-component*/} +### Шаг 1: Экспортировать компонент {/*step-1-export-the-component*/} -The `export default` prefix is a [standard JavaScript syntax](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in [Importing and Exporting Components](/learn/importing-and-exporting-components)!) +Префикс `export default` — это [стандартный синтаксис JavaScript](https://developer.mozilla.org/ru/docs/web/javascript/reference/statements/export) (не является спецификой React). Он позволяет пометить основную функцию в файле, чтобы её можно было импортировать из других файлов. (Подробнее об импорте в [Импорт и Экспорт компонентов](/learn/importing-and-exporting-components)!) -### Step 2: Define the function {/*step-2-define-the-function*/} +### Шаг 2: Определить функцию {/*step-2-define-the-function*/} -With `function Profile() { }` you define a JavaScript function with the name `Profile`. +С помощью `function Profile() { }` вы определяете JavaScript-функцию с именем `Profile`. -React components are regular JavaScript functions, but **their names must start with a capital letter** or they won't work! +React-компоненты — это обычные JavaScript функции, но **их имена должны начинаться с заглавной буквы**, иначе они не будут работать! -### Step 3: Add markup {/*step-3-add-markup*/} +### Шаг 3: Добавить разметку {/*step-3-add-markup*/} -The component returns an `` tag with `src` and `alt` attributes. `` is written like HTML, but it is actually JavaScript under the hood! This syntax is called [JSX](/learn/writing-markup-with-jsx), and it lets you embed markup inside JavaScript. +Компонент возвращает тег `` с атрибутами `src` и `alt`. `` выглядит как HTML, но на самом деле под капотом это JavaScript! Этот синтаксис называется [JSX](/learn/writing-markup-with-jsx), и он позволяет вам вставлять разметку в JavaScript. -Return statements can be written all on one line, as in this component: +Оператор `return` можно записать в одну строку, как в этом компоненте: ```js -return Katherine Johnson; +return Кэтрин Джонсон; ``` -But if your markup isn't all on the same line as the `return` keyword, you must wrap it in a pair of parentheses: +Но если вся ваша разметка не находится на той же строке, что и ключевое слово `return`, то вы должны обернуть её в пару скобок: ```js return (
        - Katherine Johnson + Кэтрин Джонсон
        ); ``` -Without parentheses, any code on the lines after `return` [will be ignored](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! +Без скобок любой код на строках после `return` [будет проигнорирован](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! -## Using a component {/*using-a-component*/} +## Использование компонента {/*using-a-component*/} -Now that you've defined your `Profile` component, you can nest it inside other components. For example, you can export a `Gallery` component that uses multiple `Profile` components: +Теперь, когда вы определили компонент `Profile`, вы можете вкладывать его в другие компоненты. Например, вы можете экспортировать компонент `Gallery`, который использует несколько компонентов `Profile`: @@ -129,7 +129,7 @@ function Profile() { return ( Katherine Johnson ); } @@ -137,7 +137,7 @@ function Profile() { export default function Gallery() { return (
        -

        Amazing scientists

        +

        Изумительные учёные

        @@ -152,37 +152,37 @@ img { margin: 0 10px 10px 0; height: 90px; } -### What the browser sees {/*what-the-browser-sees*/} +### Что видит браузер {/*what-the-browser-sees*/} -Notice the difference in casing: +Обратите внимание на разницу в регистре: -* `
        ` is lowercase, so React knows we refer to an HTML tag. -* `` starts with a capital `P`, so React knows that we want to use our component called `Profile`. +* `
        ` в нижнем регистре, поэтому React знает, что мы обращаемся к HTML-тегу. +* `` начинается с заглавной буквы `P`, поэтому React знает, что мы хотим использовать наш компонент с именем `Profile`. -And `Profile` contains even more HTML: ``. In the end, this is what the browser sees: +А `Profile` содержит ещё больше HTML: ``. В конечном итоге, вот что видит браузер: ```html
        -

        Amazing scientists

        - Katherine Johnson - Katherine Johnson - Katherine Johnson +

        Изумительные учёные

        + Кэтрин Джонсон + Кэтрин Джонсон + Кэтрин Джонсон
        ``` -### Nesting and organizing components {/*nesting-and-organizing-components*/} +### Вкладывание и организация компонентов {/*nesting-and-organizing-components*/} -Components are regular JavaScript functions, so you can keep multiple components in the same file. This is convenient when components are relatively small or tightly related to each other. If this file gets crowded, you can always move `Profile` to a separate file. You will learn how to do this shortly on the [page about imports.](/learn/importing-and-exporting-components) +Компоненты — это обычные функции JavaScript, поэтому вы можете держать несколько компонентов в одном файле. Это удобно, когда компоненты относительно небольшие или тесно связаны друг с другом. Если этот файл становится переполненным, вы всегда можете переместить `Profile` в отдельный файл. В скором времени вы узнаете, как это сделать на [странице об импортах.](/learn/importing-and-exporting-components) -Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like. +Поскольку компоненты `Profile` рендерятся внутри компонента `Gallery`—даже несколько раз!—мы можем сказать, что `Gallery` является **родительским компонентом**, который рендерит каждый `Profile` как "ребёнка". Это часть магии React: вы можете определить компонент один раз и затем использовать его в любом количестве мест и сколько угодно раз. -Components can render other components, but **you must never nest their definitions:** +Компоненты могут рендерить другие компоненты, но **вы никогда не должны вкладывать их определения:** ```js {2-5} export default function Gallery() { - // 🔴 Never define a component inside another component! + // 🔴 Никогда не определяйте компонент внутри другого компонента! function Profile() { // ... } @@ -190,47 +190,47 @@ export default function Gallery() { } ``` -The snippet above is [very slow and causes bugs.](/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state) Instead, define every component at the top level: +Код выше [очень медленный и вызывает ошибки.](/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state) Вместо этого определяйте каждый компонент на верхнем уровне: ```js {5-8} export default function Gallery() { // ... } -// ✅ Declare components at the top level +// ✅ Определяйте компоненты на верхнем уровне function Profile() { // ... } ``` -When a child component needs some data from a parent, [pass it by props](/learn/passing-props-to-a-component) instead of nesting definitions. +Если дочернему компоненту нужны данные от родительского, [передавайте их через пропсы](/learn/passing-props-to-a-component), вместо вложенных определений. -#### Components all the way down {/*components-all-the-way-down*/} +#### Компоненты на все случаи жизни {/*components-all-the-way-down*/} -Your React application begins at a "root" component. Usually, it is created automatically when you start a new project. For example, if you use [CodeSandbox](https://codesandbox.io/) or [Create React App](https://create-react-app.dev/), the root component is defined in `src/App.js`. If you use the framework [Next.js](https://nextjs.org/), the root component is defined in `pages/index.js`. In these examples, you've been exporting root components. +Ваше React-приложение начинается с "корневого" компонента. Обычно он создаётся автоматически при создании нового проекта. Например, если вы используете [CodeSandbox](https://codesandbox.io/) или [Create React App](https://create-react-app.dev/), корневой компонент определён в файле `src/App.js`. Если вы используете фреймворк [Next.js](https://nextjs.org/), корневой компонент определён в файле `pages/index.js`. В этих примерах вы экспортировали корневые компоненты. -Most React apps use components all the way down. This means that you won't only use components for reusable pieces like buttons, but also for larger pieces like sidebars, lists, and ultimately, complete pages! Components are a handy way to organize UI code and markup, even if some of them are only used once. +Большинство React-приложений используют компоненты повсюду. Это означает, что вы будете использовать компоненты не только для переиспользуемых элементов, таких как кнопки, но также для более крупных элементов: боковых панелей, списков и в конечном итоге, целых страниц! Компоненты — это удобный способ организации кода UI и разметки, даже если некоторые из них используются только один раз. -[React-based frameworks](/learn/start-a-new-react-project) take this a step further. Instead of using an empty HTML file and letting React "take over" managing the page with JavaScript, they *also* generate the HTML automatically from your React components. This allows your app to show some content before the JavaScript code loads. +[Фреймворки на основе React](/learn/start-a-new-react-project) пошли ещё дальше. Вместо того, чтобы использовать пустой файл HTML и позволять React "захватывать" управление страницей с помощью JavaScript, они *также* автоматически генерируют HTML из ваших React-компонентов. Это позволяет вашему приложению показывать часть контента до того, как загрузится JavaScript код. -Still, many websites only use React to [add interactivity to existing HTML pages.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) They have many root components instead of a single one for the entire page. You can use as much—or as little—React as you need. +Тем не менее, многие веб-сайты используют React только для [добавления интерактивности на существующие HTML-страницы.](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page) У них есть множество корневых компонентов вместо одного для всей страницы. Вы можете брать от React столько, сколько вам нужно. -You've just gotten your first taste of React! Let's recap some key points. +Вы только что познакомились с React! Давайте повторим некоторые ключевые моменты. -* React lets you create components, **reusable UI elements for your app.** -* In a React app, every piece of UI is a component. -* React components are regular JavaScript functions except: - - 1. Their names always begin with a capital letter. - 2. They return JSX markup. +* React позволяет вам создавать компоненты, **переиспользуемые элементы UI для вашего приложения.** +* В React-приложении каждый элемент UI это компонент. +* Компоненты React — это обычные функции JavaScript, за исключением того, что: + + 1. Их имена всегда начинаются с заглавной буквы. + 2. Они возвращают разметку JSX. @@ -238,9 +238,9 @@ You've just gotten your first taste of React! Let's recap some key points. -#### Export the component {/*export-the-component*/} +#### Экспортируйте компонент {/*export-the-component*/} -This sandbox doesn't work because the root component is not exported: +Этот пример не работает из-за того, что корневой компонент не экспортирован: @@ -249,7 +249,7 @@ function Profile() { return ( Aklilu Lemma ); } @@ -261,11 +261,11 @@ img { height: 181px; } -Try to fix it yourself before looking at the solution! +Попробуйте исправить его самостоятельно прежде чем смотреть в решение! -Add `export default` before the function definition like so: +Добавьте `export default` перед определением функции, вот так: @@ -274,7 +274,7 @@ export default function Profile() { return ( Aklilu Lemma ); } @@ -286,17 +286,17 @@ img { height: 181px; } -You might be wondering why writing `export` alone is not enough to fix this example. You can learn the difference between `export` and `export default` in [Importing and Exporting Components.](/learn/importing-and-exporting-components) +Возможно, вы задаётесь вопросом, почему написать лишь `export` недостаточно, чтобы исправить этот пример. Вы можете узнать разницу между `export` и `export default` в разделе [Импорт и Экспорт компонентов.](/learn/importing-and-exporting-components) -#### Fix the return statement {/*fix-the-return-statement*/} +#### Исправьте оператор return {/*fix-the-return-statement*/} -Something isn't right about this `return` statement. Can you fix it? +Что-то не так с оператором `return`. Сможете его исправить? -You may get an "Unexpected token" error while trying to fix this. In that case, check that the semicolon appears *after* the closing parenthesis. Leaving a semicolon inside `return ( )` will cause an error. +При попытке исправить оператор вы можете получить ошибку "Unexpected token". В этом случае убедитесь, что точка с запятой находится *после* закрывающей скобки. Оставив точку с запятой внутри `return ( )`, вы вызовите ошибку. @@ -306,7 +306,7 @@ You may get an "Unexpected token" error while trying to fix this. In that case, ```js export default function Profile() { return - Katsuko Saruhashi; + Кацуко Сарухаси; } ``` @@ -318,13 +318,13 @@ img { height: 180px; } -You can fix this component by moving the return statement to one line like so: +Вы можете исправить этот компонент, записав оператор `return` в одну строку, вот так: ```js export default function Profile() { - return Katsuko Saruhashi; + return Кацуко Сарухаси; } ``` @@ -334,7 +334,7 @@ img { height: 180px; } -Or by wrapping the returned JSX markup in parentheses that open right after `return`: +Или обернув возвращаемуе JSX разметку в скобки, которые открываются сразу после `return`: @@ -343,7 +343,7 @@ export default function Profile() { return ( Katsuko Saruhashi ); } @@ -357,9 +357,9 @@ img { height: 180px; } -#### Spot the mistake {/*spot-the-mistake*/} +#### Найдите ошибку {/*spot-the-mistake*/} -Something's wrong with how the `Profile` component is declared and used. Can you spot the mistake? (Try to remember how React distinguishes components from the regular HTML tags!) +Что-то не так с тем, как объявлен и использован компонент `Profile`. Сможете найти ошибку? (Попробуйте вспомнить, как React отличает компоненты от обычных тегов HTML!) @@ -368,7 +368,7 @@ function profile() { return ( Alan L. Hart ); } @@ -376,7 +376,7 @@ function profile() { export default function Gallery() { return (
        -

        Amazing scientists

        +

        Изумительные учёные

        @@ -393,9 +393,9 @@ img { margin: 0 10px 10px 0; height: 90px; } -React component names must start with a capital letter. +Имена React-компонентов должны начинаться с заглавной буквы. -Change `function profile()` to `function Profile()`, and then change every `` to ``: +Замените `function profile()` на `function Profile()`, а затем каждый `` на ``: @@ -404,7 +404,7 @@ function Profile() { return ( Alan L. Hart ); } @@ -412,7 +412,7 @@ function Profile() { export default function Gallery() { return (
        -

        Amazing scientists

        +

        Изумительные учёные

        @@ -429,14 +429,14 @@ img { margin: 0 10px 10px 0; } -#### Your own component {/*your-own-component*/} +#### Ваш компонент {/*your-own-component*/} -Write a component from scratch. You can give it any valid name and return any markup. If you're out of ideas, you can write a `Congratulations` component that shows `

        Good job!

        `. Don't forget to export it! +Напишите компонент с нуля. Вы можете дать ему любое допустимое имя и вернуть любую разметку. Если ничего не приходит на ум, то вы можете написать компонент `Congratulations`, который отображает заголовок `

        Хорошая работа!

        `. Не забудьте экспортировать компонент! ```js -// Write your component below! +// Напишите свой компонент ниже! ``` @@ -449,7 +449,7 @@ Write a component from scratch. You can give it any valid name and return any ma ```js export default function Congratulations() { return ( -

        Good job!

        +

        Хорошая работа!

        ); } ```