diff --git a/content/docs/add-react-to-a-website.md b/content/docs/add-react-to-a-website.md index 11b99d37a..f6da02b05 100644 --- a/content/docs/add-react-to-a-website.md +++ b/content/docs/add-react-to-a-website.md @@ -1,6 +1,6 @@ --- id: add-react-to-a-website -title: Add React to a Website +title: Добавляем React на сайт permalink: docs/add-react-to-a-website.html redirect_from: - "docs/add-react-to-an-existing-app.html" @@ -8,127 +8,127 @@ prev: getting-started.html next: create-a-new-react-app.html --- -Use as little or as much React as you need. +Вы можете использовать React в том объёме, в котором вам хочется. -React has been designed from the start for gradual adoption, and **you can use as little or as much React as you need**. Perhaps you only want to add some "sprinkles of interactivity" to an existing page. React components are a great way to do that. +Для внедрения React не надо ничего переписывать. **Его можно использовать как для маленькой кнопки, так и для целого приложения.** Возможно, вы захотите лишь чуть «оживить» некоторые элементы на вашей странице. React-компоненты подходят для этого как нельзя лучше. -The majority of websites aren't, and don't need to be, single-page apps. With **a few lines of code and no build tooling**, try React in a small part of your website. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets. +Большинство сайтов в Интернете является обычными HTML-страницами. Даже если ваш сайт не относится к одностраничным приложениям, вы можете добавить в него React, написав **всего несколько строк кода без каких-либо инструментов сборки**. В зависимости от целей, вы можете постепенно переносить на React весь сайт, а можете переписать всего несколько виджетов. --- -- [Add React in One Minute](#add-react-in-one-minute) -- [Optional: Try React with JSX](#optional-try-react-with-jsx) (no bundler necessary!) +- [Добавляем React за одну минуту](#add-react-in-one-minute) +- [Необязательно: Используем React с JSX](#optional-try-react-with-jsx) (без каких-либо бандлеров!) -## Add React in One Minute {#add-react-in-one-minute} +## Добавляем React за одну минуту {#add-react-in-one-minute} -In this section, we will show how to add a React component to an existing HTML page. You can follow along with your own website, or create an empty HTML file to practice. +В этом разделе вы научитесь добавлять React на существующую HTML-страницу. Вы можете практиковаться на своём собственном сайте или создать для этого пустой HTML файл. -There will be no complicated tools or install requirements -- **to complete this section, you only need an internet connection, and a minute of your time.** +Мы не будем пользоваться сложными инструментами сборки или что-то устанавливать. **Всё, что вам нужно -- это доступ к Интернету и минута свободного времени**. -Optional: [Download the full example (2KB zipped)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip) +Необязательно: [скачать готовый пример (архив 2 Кбайт)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip) -### Step 1: Add a DOM Container to the HTML {#step-1-add-a-dom-container-to-the-html} +### Шаг 1: Добавляем DOM-контейнер в HTML {#step-1-add-a-dom-container-to-the-html} -First, open the HTML page you want to edit. Add an empty `
` tag to mark the spot where you want to display something with React. For example: +Для начала, откройте HTML файл страницы, которую хотите отредактировать. Добавьте пустой тег `
` в месте, где вы хотите отобразить что-нибудь с помощью React. Например: ```html{3} - +
- + ``` -We gave this `
` a unique `id` HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it. +Затем назначьте созданному `
` уникальный атрибут `id`. Это позволит впоследствии найти тег из JavaScript кода и отобразить React-компоненты внутри него. ->Tip +>Совет > ->You can place a "container" `
` like this **anywhere** inside the `` tag. You may have as many independent DOM containers on one page as you need. They are usually empty -- React will replace any existing content inside DOM containers. +>«Контейнер» `
` можно поместить **где угодно** внутри тега ``. Вы можете создать любое количество независимых DOM-контейнеров на одной странице. Эти контейнеры принято оставлять пустыми, так как React в любом случае заменяет всё их содержимое. -### Step 2: Add the Script Tags {#step-2-add-the-script-tags} +### Шаг 2: Добавляем script-теги {#step-2-add-the-script-tags} -Next, add three ` - + ``` -The first two tags load React. The third one will load your component code. +Первые два тега загружают React. Третий тег загружает код вашего собственного компонента. -### Step 3: Create a React Component {#step-3-create-a-react-component} +### Шаг 3: Создаём React-компонент {#step-3-create-a-react-component} -Create a file called `like_button.js` next to your HTML page. +Создайте файл с именем `like_button.js` рядом с вашим HTML файлом. -Open **[this starter code](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)** and paste it into the file you created. +Возьмите **[этот стартовый код](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)** и вставьте его в созданный ранее файл. ->Tip +>Совет > ->This code defines a React component called `LikeButton`. Don't worry if you don't understand it yet -- we'll cover the building blocks of React later in our [hands-on tutorial](/tutorial/tutorial.html) and [main concepts guide](/docs/hello-world.html). For now, let's just get it showing on the screen! +>В данном коде создаётся React-компонент с именем `LikeButton`. Не беспокойтесь, если что-то кажется вам непонятным -- мы подробно разберём принципы разработки на React позже, в нашем [практическом руководстве](/tutorial/tutorial.html) и во [введении в основные понятия](/docs/hello-world.html). Пока же мы просто посмотрим, как это выглядит на экране. -After **[the starter code](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)**, add two lines to the bottom of `like_button.js`: +Добавьте ещё 2 строки в конец файла `like_button.js`, после **[стартового кода](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)**: ```js{3,4} -// ... the starter code you pasted ... +// ... стартовый код ... const domContainer = document.querySelector('#like_button_container'); ReactDOM.render(e(LikeButton), domContainer); ``` -These two lines of code find the `
` we added to our HTML in the first step, and then display our "Like" button React component inside of it. +Этот код ищет контейнер `
`, который мы добавили на первом шаге, а затем отображает наш React-компонент с кнопкой «Like» внутри него. -### That's It! {#thats-it} +### Готово! {#thats-it} -There is no step four. **You have just added the first React component to your website.** +Вот и всё! **Вы только что добавили свой первый React-компонент на страницу.** -Check out the next sections for more tips on integrating React. +Перейдите к следующим разделам, если хотите узнать о других способах добавить React. -**[View the full example source code](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605)** +**[Посмотреть финальный код примера](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605)** -**[Download the full example (2KB zipped)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)** +**[Скачать код примера (архив 2 Кбайт)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)** -### Tip: Reuse a Component {#tip-reuse-a-component} +### Совет: Повторное использование компонентов {#tip-reuse-a-component} -Commonly, you might want to display React components in multiple places on the HTML page. Here is an example that displays the "Like" button three times and passes some data to it: +Зачастую, вам может понадобиться отобразить React-компонент в нескольких местах одной и той же HTML-страницы. Вот как можно показать сразу три кнопки «Like» с разными данными: -[View the full example source code](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda) +[Посмотреть исходный код примера](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda) -[Download the full example (2KB zipped)](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/9d0dd0ee941fea05fd1357502e5aa348abb84c12.zip) +[Скачать код примера (архив 2 Кбайт)](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/9d0dd0ee941fea05fd1357502e5aa348abb84c12.zip) ->Note +>Примечание > ->This strategy is mostly useful while React-powered parts of the page are isolated from each other. Inside React code, it's easier to use [component composition](/docs/components-and-props.html#composing-components) instead. +>Этот способ лучше всего подходит для страниц, содержащих несколько изолированных участков кода, написанных на React. Внутри чистого React-кода проще использовать [композицию компонентов](/docs/components-and-props.html#composing-components). -### Tip: Minify JavaScript for Production {#tip-minify-javascript-for-production} +### Совет: Минификация JavaScript для продакшена {#tip-minify-javascript-for-production} -Before deploying your website to production, be mindful that unminifed JavaScript can significantly slow down the page for your users. +Публикуя ваш сайт на продакшен, имейте в виду, что несжатый JavaScript значительно замедляет страницу для ваших пользователей. -If you already minify the application scripts, **your site will be production-ready** if you ensure that the deployed HTML loads the versions of React ending in `production.min.js`: +Если вы уже минифицируете свои скрипты, то не забудьте подготовить к продакшену сам React. Для этого поменяйте окончания ссылок на React на `production.min.js`: ```js ``` -If you don't have a minification step for your scripts, [here's one way to set it up](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3). +Если же вы не настроили минификацию для ваших скриптов, то [вот один из вариантов, как это сделать](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3). -## Optional: Try React with JSX {#optional-try-react-with-jsx} +## Необязательно: Используем React с JSX {#optional-try-react-with-jsx} -In the examples above, we only relied on features that are natively supported by the browsers. This is why we used a JavaScript function call to tell React what to display: +В предыдущих примерах мы не выходили за рамки обычных браузерных возможностей. В частности, мы указываем, что React должен выводить на экран, просто вызывая JavaScript-функцию: ```js const e = React.createElement; -// Display a "Like"