diff --git a/src/content/learn/editor-setup.md b/src/content/learn/editor-setup.md index 94dbbbaeff..1ba4f365c4 100644 --- a/src/content/learn/editor-setup.md +++ b/src/content/learn/editor-setup.md @@ -1,62 +1,62 @@ --- -title: Editor Setup +title: Настройка редактора --- -A properly configured editor can make code clearer to read and faster to write. It can even help you catch bugs as you write them! If this is your first time setting up an editor or you're looking to tune up your current editor, we have a few recommendations. +Правильно настроенный редактор упрощает чтение и ускоряет написание кода. Он также помогает находить баги прямо во время работы с кодом. Если вы настраиваете редактор впервые или хотите улучшить текущее поведение редактора, у нас есть несколько рекомендаций. -* What the most popular editors are -* How to format your code automatically +* Какие редакторы являются наиболее популярными +* Как автоматически форматировать код -## Your editor {/*your-editor*/} +## Ваш редактор {/*your-editor*/} -[VS Code](https://code.visualstudio.com/) is one of the most popular editors in use today. It has a large marketplace of extensions and integrates well with popular services like GitHub. Most of the features listed below can be added to VS Code as extensions as well, making it highly configurable! +[VS Code](https://code.visualstudio.com/) — один из наиболее популярных редакторов. Он имеет огромный набор расширений и отлично интегрирует популярные сервисы, такие как GitHub. Большинство из перечисленных ниже инструментов можно добавить в VS Code как расширения. -Other popular text editors used in the React community include: +Другие популярные текстовые редакторы, используемые React-разработчиками: -* [WebStorm](https://www.jetbrains.com/webstorm/) is an integrated development environment designed specifically for JavaScript. -* [Sublime Text](https://www.sublimetext.com/) has support for JSX and TypeScript, [syntax highlighting](https://stackoverflow.com/a/70960574/458193) and autocomplete built in. -* [Vim](https://www.vim.org/) is a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems and with Apple OS X. +* [WebStorm](https://www.jetbrains.com/webstorm/) — интегрированная среда разработки, спроектированная специально для JavaScript. +* [Sublime Text](https://www.sublimetext.com/) — редактор с поддержкой JSX и TypeScript, [подсветкой синтаксиса](https://stackoverflow.com/a/70960574/458193) и встроенным автозаполнением. +* [Vim](https://www.vim.org/) — текстовый редактор с возможностью глубокой настройки инструментов, позволяет работать с любым форматом текста быстро и эффективно. Он встроен в большинство UNIX-систем и Apple OS X как "vi". -## Recommended text editor features {/*recommended-text-editor-features*/} +## Рекомендуемые инструменты текстового редактора {/*recommended-text-editor-features*/} -Some editors come with these features built in, but others might require adding an extension. Check to see what support your editor of choice provides to be sure! +Некоторые из инструментов уже встроены в редакторы, другие устанавливаются дополнительно как плагины или расширения. -### Linting {/*linting*/} +### Отладчик {/*linting*/} + +Отладчики находят проблемы во время написания кода, что позволяет исправлять их сразу же. [ESLint](https://eslint.org/) — популярный отладчик для JavaScript с открытым исходным кодом. -Code linters find problems in your code as you write, helping you fix them early. [ESLint](https://eslint.org/) is a popular, open source linter for JavaScript. +* [Установка ESLint с рекомендуемыми настройками для React](https://www.npmjs.com/package/eslint-config-react-app) (убедитесь в том, что у вас [установлен Node!](https://nodejs.org/en/download/current/)) +* [Интеграция ESLint в VS Code при помощи официального расширения](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) -* [Install ESLint with the recommended configuration for React](https://www.npmjs.com/package/eslint-config-react-app) (be sure you have [Node installed!](https://nodejs.org/en/download/current/)) -* [Integrate ESLint in VSCode with the official extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) +**Убедитесь в том, что все правила [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) включены для вашего проекта.** Это базовые правила, позволяющие обнаружить большинство распространенных багов на ранней стадии. Рекомендованный пресет [`eslint-config-react-app`](https://www.npmjs.com/package/eslint-config-react-app) уже включает эти правила. -**Make sure that you've enabled all the [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) rules for your project.** They are essential and catch the most severe bugs early. The recommended [`eslint-config-react-app`](https://www.npmjs.com/package/eslint-config-react-app) preset already includes them. +### Форматирование {/*formatting*/} -### Formatting {/*formatting*/} +При работе в команде никому не хочется вести диалоги на тему ["пробелы vs табы"](https://www.google.com/search?q=tabs+vs+spaces). К счастью, [Prettier](https://prettier.io/) позволяет автоматически форматировать код на основе заданных параметров. Запустите Prettier и ваш код будет отформатирован, включая отступы и кавычки. В идеале Prettier будет запускаться во время сохранения файла, быстро применяя все необходимые изменения. -The last thing you want to do when sharing your code with another contributor is get into an discussion about [tabs vs spaces](https://www.google.com/search?q=tabs+vs+spaces)! Fortunately, [Prettier](https://prettier.io/) will clean up your code by reformatting it to conform to preset, configurable rules. Run Prettier, and all your tabs will be converted to spaces—and your indentation, quotes, etc will also all be changed to conform to the configuration. In the ideal setup, Prettier will run when you save your file, quickly making these edits for you. +Вы можете установить [расширение Prettier в VS Code](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) следуя простой инструкции: -You can install the [Prettier extension in VSCode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) by following these steps: +1. Запустите VS Code +2. Откройте функцию "Перейти к файлу" (нажмите Ctrl/Cmd+P) +3. Вставьте команду `ext install esbenp.prettier-vscode` +4. Нажмите Enter -1. Launch VS Code -2. Use Quick Open (press Ctrl/Cmd+P) -3. Paste in `ext install esbenp.prettier-vscode` -4. Press Enter +#### Форматирование при сохранении {/*formatting-on-save*/} -#### Formatting on save {/*formatting-on-save*/} +В идеале следует форматировать код при каждом сохранении. В VS Code для этого есть своя настройка! -Ideally, you should format your code on every save. VS Code has settings for this! +1. В VS Code нажмите `CTRL/CMD + SHIFT + P`. +2. Введите "settings" +3. Нажмите Enter +4. В поиске введите "format on save" +5. Убедитесь, что настройка "format on save" включена! -1. In VS Code, press `CTRL/CMD + SHIFT + P`. -2. Type "settings" -3. Hit Enter -4. In the search bar, type "format on save" -5. Be sure the "format on save" option is ticked! - -> If your ESLint preset has formatting rules, they may conflict with Prettier. We recommend disabling all formatting rules in your ESLint preset using [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) so that ESLint is *only* used for catching logical mistakes. If you want to enforce that files are formatted before a pull request is merged, use [`prettier --check`](https://prettier.io/docs/en/cli.html#--check) for your continuous integration. +> Если в пресете ESLint есть правила форматирования, они могут конфликтовать с Prettier. Мы рекомендуем отключить все правила форматирования в ESLint пресете используя [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier). Так ESLint будет использоваться *только* для отслеживания логических ошибок. Если вы хотите, чтобы файлы форматировались до того, как запрос на слияние будет выполнен, используйте [`prettier --check`](https://prettier.io/docs/en/cli.html#--check) для вашей непрерывной интеграции. diff --git a/src/content/learn/writing-markup-with-jsx.md b/src/content/learn/writing-markup-with-jsx.md index 62670150ac..de8571fd14 100644 --- a/src/content/learn/writing-markup-with-jsx.md +++ b/src/content/learn/writing-markup-with-jsx.md @@ -1,34 +1,36 @@ --- -title: Writing Markup with JSX +title: Написание JSX разметки --- -*JSX* is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it. +*JSX* - это синтаксическое расширение для JavaScript, позволяющее писать похожую на HTML разметку внутри JavaScript файлов. Несмотря на то, что существуют и другие способы написания компонентов, большинство React разработчиков предпочитают лаконичность JSX. Поэтому JSX встречается во многих кодовых базах. -* Why React mixes markup with rendering logic -* How JSX is different from HTML -* How to display information with JSX +* Почему React смешивает разметку и логику рендеринга +* Чем JSX отличается от HTML +* Как отображать информацию, используя JSX -## JSX: Putting markup into JavaScript {/*jsx-putting-markup-into-javascript*/} +## JSX: Встраивание разметки в JavaScript {/*jsx-putting-markup-into-javascript*/} The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page's logic lived separately in JavaScript: +Веб-сайты состоят из HTML, CSS и JavaScript. Долгое время разработчики использовали отдельные файлы: HTML для контента, CSS для дизайна и JavaScript для логики. + - + HTML - + JavaScript @@ -36,53 +38,53 @@ JavaScript -But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why **in React, rendering logic and markup live together in the same place—components.** +Со временем веб-сайты становились более интерактивными и логика начала определять содержание. JavaScript начал отвечать за HTML! Именно поэтому **в React логика рендеринга и разметка находятся в одном месте — в компонентах.** - + -`Sidebar.js` React component +React-компонент `Sidebar.js` - + -`Form.js` React component +React компонент `Form.js` -Keeping a button's rendering logic and markup together ensures that they stay in sync with each other on every edit. Conversely, details that are unrelated, such as the button's markup and a sidebar's markup, are isolated from each other, making it safer to change either of them on their own. +Размещая логику рендера и разметку кнопки вместе обеспечивается их синхронизация при всех дальнейших изменениях. И наоборот, размещая несвязанные детали отдельно, например разметку кнопки и разметку сайдбара, они становятся изолированными друг от друга. Поэтому дальнейшие изменение разметки одного из компонентов будет более безопасным. -Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. The best way to understand this is to convert some HTML markup to JSX markup. +Каждый React компонент — это JavaScript функция с разметкой, которую React рендерит в браузер. React компоненты используют синтаксическое расширение JSX чтобы определить файл как компонент с разметкой. JSX очень похож на HTML, но является более строгим и позволяет отображать динамическую информацию. Лучший способ понять, как работает JSX — конвертировать HTML разметку в JSX разметку. -JSX and React are two separate things. They're often used together, but you *can* [use them independently](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform) of each other. JSX is a syntax extension, while React is a JavaScript library. +JSX и React — это две разные вещи. Они часто используются вместе, но вы *можете* [использовать их отдельно](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform). JSX — это синтаксическое расширение, в то время как React — это JavaScript библиотека. -## Converting HTML to JSX {/*converting-html-to-jsx*/} +## Конвертация HTML в JSX {/*converting-html-to-jsx*/} -Suppose that you have some (perfectly valid) HTML: +Предположим, что у вас есть (полностью валидный) HTML: ```html -

Hedy Lamarr's Todos

+

Задачи Hedy Lamarr's

Hedy Lamarr ``` -And you want to put it into your component: +И вы хотите разместить эту разметку в компоненте: ```js export default function TodoList() { @@ -92,25 +94,24 @@ export default function TodoList() { } ``` -If you copy and paste it as is, it will not work: - +Если вы просто скопируете и вставите разметку, компонент не будет работать: ```js export default function TodoList() { return ( - // This doesn't quite work! -

Hedy Lamarr's Todos

+ // Этот код не работает! +

Задачи Hedy Lamarr's

Hedy Lamarr ); } @@ -122,25 +123,25 @@ img { height: 90px }
-This is because JSX is stricter and has a few more rules than HTML! If you read the error messages above, they'll guide you to fix the markup, or you can follow the guide below. +JSX более строгий и у него есть немного больше правил, чем у HTML! Обратите внимание на сообщение в ошибке выше, оно подскажет вам, как исправить разметку. Или просто следуйте инструкции ниже. -Most of the time, React's on-screen error messages will help you find where the problem is. Give them a read if you get stuck! +В большинстве ситуаций ошибки React на экране подскажут вам, в чем заключается проблема. Ознакамливайтесь с ними, если у вас что-то не получается! -## The Rules of JSX {/*the-rules-of-jsx*/} +## Правила JSX {/*the-rules-of-jsx*/} -### 1. Return a single root element {/*1-return-a-single-root-element*/} +### 1. Возвращайте один корневой элемент {/*1-return-a-single-root-element*/} -To return multiple elements from a component, **wrap them with a single parent tag.** +Если вам нужно вернуть несколько элементов в компоненте, **оберните их в один родительский тег.** -For example, you can use a `
`: +Например, можно использовать `
`: ```js {1,11}
-

Hedy Lamarr's Todos

+

Задачи Hedy Lamarr's

Hedy Lamarr`: ``` -If you don't want to add an extra `
` to your markup, you can write `<>` and `` instead: +Если вы не хотите добавлять дополнительный `
` в разметку, можно воспользоваться тегами `<>` и ``: ```js {1,11} <> -

Hedy Lamarr's Todos

+

Задачи Hedy Lamarr's

Hedy Lamarr` to your markup, you can write `<>` and ``` -This empty tag is called a *[Fragment.](/reference/react/Fragment)* Fragments let you group things without leaving any trace in the browser HTML tree. +Этот пустой тег называется *[Фрагмент.](/reference/react/Fragment)* Фрагменты позволяют группировать элементы разметки не внедряя дополнительные теги и не изменяя древо HTML в браузере. -#### Why do multiple JSX tags need to be wrapped? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/} +#### Почему несколько JSX тегов нужно объединять? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/} -JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can't return two objects from a function without wrapping them into an array. This explains why you also can't return two JSX tags without wrapping them into another tag or a Fragment. +JSX выглядит так же как HTML, но внутри конвертируется в обычные JavaScript объекты. Нельзя вернуть два объекта из функции без объединения в один массив. Это также объясняет почему нельзя возвращать два JSX тега без их объединения в один тег или Фрагмент. -### 2. Close all the tags {/*2-close-all-the-tags*/} - -JSX requires tags to be explicitly closed: self-closing tags like `` must become ``, and wrapping tags like `
  • oranges` must be written as `
  • oranges
  • `. +### 2. Закрывайте все теги {/*2-close-all-the-tags*/} -This is how Hedy Lamarr's image and list items look closed: +JSX требует закрывать все теги: самозакрывающиеся теги, такие как `` должны меняться на ``, а объединяющие теги, такие как `
  • oranges` должны изменяться на `
  • oranges
  • `. +Вот так изображение Hedy Lamarr и список выглядят закрытыми: ```js {2-6,8-10} <> @@ -193,18 +193,18 @@ This is how Hedy Lamarr's image and list items look closed: class="photo" />
      -
    • Invent new traffic lights
    • -
    • Rehearse a movie scene
    • -
    • Improve the spectrum technology
    • +
    • Придумать новые светофоры +
    • Отрепетировать сцену из фильма +
    • Улучшить спектральный сенсор
    ``` -### 3. camelCase all most of the things! {/*3-camelcase-salls-most-of-the-things*/} +### 3. Используйте camelCase для всех большинства вещей! {/*3-camelcase-salls-most-of-the-things*/} -JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can't contain dashes or be reserved words like `class`. +JSX конвертируется в JavaScript и все атрибуты становятся ключами JavaScript объекта. В компонентах вам часто потребуется считывать эти атрибуты и присваивать переменным. Но в JavaScript есть ограничения для названий переменных. Например, переменные не могут содержать тире или или называться так само, как и зарезервированные слова, например `class`. -This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of `stroke-width` you use `strokeWidth`. Since `class` is a reserved word, in React you write `className` instead, named after the [corresponding DOM property](https://developer.mozilla.org/en-US/docs/Web/API/Element/className): +Поэтому в React для большинства HTML и SVG атрибутов используется camelCase. Например, вместо `stroke-width` следует использовать `strokeWidth`. Поскольку `class` — зарезервированное слово, вместо него в React следует использовать `className`, название, [соответствующее свойству DOM](https://developer.mozilla.org/en-US/docs/Web/API/Element/className): ```js {4} ``` -You can [find all these attributes in the list of DOM component props.](/reference/react-dom/components/common) If you get one wrong, don't worry—React will print a message with a possible correction to the [browser console.](https://developer.mozilla.org/docs/Tools/Browser_Console) +Вы можете [найти все эти атрибуты в списке свойств DOM компонентов.](/reference/react-dom/components/common) Если вы напишите атрибут неправильно, React покажет сообщение с возможным решением проблемы в [консоли браузера.](https://developer.mozilla.org/docs/Tools/Browser_Console) -For historical reasons, [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) and [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) attributes are written as in HTML with dashes. +По историческим причинам атрибуты [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) и [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) пишутся с тире, как и в HTML. -### Pro-tip: Use a JSX Converter {/*pro-tip-use-a-jsx-converter*/} +### Подсказка: Используйте конвертор JSX {/*pro-tip-use-a-jsx-converter*/} -Converting all these attributes in existing markup can be tedious! We recommend using a [converter](https://transform.tools/html-to-jsx) to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it's still worth understanding what is going on so that you can comfortably write JSX on your own. +Конвертация всех атрибутов в уже существующей разметке может быть утомительной. Мы рекомендуем использовать [конвертор](https://transform.tools/html-to-jsx) чтобы конвертировать уже существующую HTML разметку в JSX. Конверторы очень полезны на практике, но вам все равно следует понимать правила, чтобы без проблем писать JSX самостоятельно. -Here is your final result: +Вот финальный результат: @@ -234,16 +234,16 @@ Here is your final result: export default function TodoList() { return ( <> -

    Hedy Lamarr's Todos

    +

    Задачи Hedy Lamarr's

    Hedy Lamarr
      -
    • Invent new traffic lights
    • -
    • Rehearse a movie scene
    • -
    • Improve the spectrum technology
    • +
    • Придумать новые светофоры +
    • Отрепетировать сцену из фильма +
    • Улучшить спектральный сенсор
    ); @@ -258,11 +258,11 @@ img { height: 90px } -Now you know why JSX exists and how to use it in components: +Теперь вы знаете, почему существует JSX и как его использовать в компонентах: -* React components group rendering logic together with markup because they are related. -* JSX is similar to HTML, with a few differences. You can use a [converter](https://transform.tools/html-to-jsx) if you need to. -* Error messages will often point you in the right direction to fixing your markup. +* React компоненты объединяют логику рендеринга и разметку, потому что они связаны между собой. +* JSX похож на HTML, но имеет свои отличия. При необходимости вы можете использовать [конвертор](https://transform.tools/html-to-jsx). +* Сообщения с ошибками зачастую направят вас в нужном направлении для решения ошибок разметки. @@ -270,9 +270,9 @@ Now you know why JSX exists and how to use it in components: -#### Convert some HTML to JSX {/*convert-some-html-to-jsx*/} +#### Конвертируйте HTML в JSX {/*convert-some-html-to-jsx*/} -This HTML was pasted into a component, but it's not valid JSX. Fix it: +Эта HTML разметка была перенесена в компонент, но это неправильный JSX. Исправьте его: @@ -280,12 +280,12 @@ This HTML was pasted into a component, but it's not valid JSX. Fix it: export default function Bio() { return (
    -

    Welcome to my website!

    +

    Добро пожаловать на мой сайт!

    - You can find my thoughts here. + Здесь я публикую свои мысли.

    - And pictures of scientists! + И изображения ученых!

    ); } @@ -308,7 +308,7 @@ export default function Bio() {
    -Whether to do it by hand or using the converter is up to you! +Вы можете конвертировать HTML самостоятельно или воспользоваться конвертором. @@ -319,12 +319,12 @@ export default function Bio() { return (
    -

    Welcome to my website!

    +

    Добро пожаловать на мой сайт!

    - You can find my thoughts here. + Здесь я публикую свои мысли.

    - And pictures of scientists! + И изображения ученых!

    );