Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 56 additions & 56 deletions src/content/learn/javascript-in-jsx-with-curly-braces.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ title: JavaScript in JSX with Curly Braces

<Intro>

JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to open a window to JavaScript.
JSX позволяет писать разметку в стиле HTML прямо в файле JavaScript, сохраняя логику рендеринга и контент в одном месте. Иногда вам захочется добавить немного JavaScript-логики или сослаться на динамическое свойство внутри этой разметки. В такой ситуации вы можете использовать фигурные скобки в вашем JSX, чтобы открыть окно в JavaScript.

</Intro>

<YouWillLearn>

* How to pass strings with quotes
* How to reference a JavaScript variable inside JSX with curly braces
* How to call a JavaScript function inside JSX with curly braces
* How to use a JavaScript object inside JSX with curly braces
* Как передавать строки в кавычках
* Как ссылаться на переменную JavaScript внутри JSX с помощью фигурных скобок
* Как вызывать функцию JavaScript внутри JSX с помощью фигурных скобок
* Как использовать объект JavaScript внутри JSX с помощью фигурных скобок

</YouWillLearn>

## Passing strings with quotes {/*passing-strings-with-quotes*/}
## Передача строк в кавычках {/*passing-strings-with-quotes*/}

When you want to pass a string attribute to JSX, you put it in single or double quotes:
Когда вы хотите передать строковый атрибут в JSX, вы заключаете его в одинарные или двойные кавычки:

<Sandpack>

Expand All @@ -41,9 +41,9 @@ export default function Avatar() {

</Sandpack>

Here, `"https://i.imgur.com/7vQD0fPs.jpg"` and `"Gregorio Y. Zara"` are being passed as strings.
Здесь `"https://i.imgur.com/7vQD0fPs.jpg"` и `"Gregorio Y. Zara"` передаются как строки.

But what if you want to dynamically specify the `src` or `alt` text? You could **use a value from JavaScript by replacing `"` and `"` with `{` and `}`**:
Но что, если вы хотите динамически указать `src` или `alt` текст? Вы можете **использовать значение из JavaScript, заменив `"` и `"` на `{` и `}`**:

<Sandpack>

Expand All @@ -67,11 +67,11 @@ export default function Avatar() {

</Sandpack>

Notice the difference between `className="avatar"`, which specifies an `"avatar"` CSS class name that makes the image round, and `src={avatar}` that reads the value of the JavaScript variable called `avatar`. That's because curly braces let you work with JavaScript right there in your markup!
Обратите внимание на разницу между `className="avatar"`, который указывает CSS-класс `"avatar"`, делающий изображение круглым, и `src={avatar}`, который считывает значение переменной JavaScript с именем `avatar`. Это потому, что фигурные скобки позволяют вам работать с JavaScript прямо в вашей разметке!

## Using curly braces: A window into the JavaScript world {/*using-curly-braces-a-window-into-the-javascript-world*/}
## Использование фигурных скобок: окно в мир JavaScript {/*using-curly-braces-a-window-into-the-javascript-world*/}

JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces `{ }`. The example below first declares a name for the scientist, `name`, then embeds it with curly braces inside the `<h1>`:
JSX — это особый способ написания JavaScript. Это означает, что внутри него можно использовать JavaScript — с помощью фигурных скобок `{ }`. В приведенном ниже примере сначала объявляется имя ученого `name`, а затем оно встраивается с помощью фигурных скобок в `<h1>`:

<Sandpack>

Expand All @@ -86,9 +86,9 @@ export default function TodoList() {

</Sandpack>

Try changing the `name`'s value from `'Gregorio Y. Zara'` to `'Hedy Lamarr'`. See how the list title changes?
Попробуйте изменить значение `name` с `'Gregorio Y. Zara'` на `'Hedy Lamarr'`. Видите, как меняется заголовок списка?

Any JavaScript expression will work between curly braces, including function calls like `formatDate()`:
Любое выражение JavaScript будет работать между фигурными скобками, включая вызовы функций, такие как `formatDate()`:

<Sandpack>

Expand All @@ -111,18 +111,18 @@ export default function TodoList() {

</Sandpack>

### Where to use curly braces {/*where-to-use-curly-braces*/}
### Где использовать фигурные скобки {/*where-to-use-curly-braces*/}

You can only use curly braces in two ways inside JSX:
Вы можете использовать фигурные скобки в JSX только двумя способами:

1. **As text** directly inside a JSX tag: `<h1>{name}'s To Do List</h1>` works, but `<{tag}>Gregorio Y. Zara's To Do List</{tag}>` will not.
2. **As attributes** immediately following the `=` sign: `src={avatar}` will read the `avatar` variable, but `src="{avatar}"` will pass the string `"{avatar}"`.
1. **Как текст** непосредственно внутри JSX-тега: `<h1>{name}'s To Do List</h1>` работает, но `<{tag}>Gregorio Y. Zara's To Do List</{tag}>` — нет.
2. **Как атрибуты** сразу после знака `=` : `src={avatar}` прочитает переменную `avatar`, но `src="{avatar}"` передаст строку `"{avatar}"`.

## Using "double curlies": CSS and other objects in JSX {/*using-double-curlies-css-and-other-objects-in-jsx*/}
## Использование «двойных фигурных скобок»: CSS и другие объекты в JSX {/*using-double-curlies-css-and-other-objects-in-jsx*/}

In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like `{ name: "Hedy Lamarr", inventions: 5 }`. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: `person={{ name: "Hedy Lamarr", inventions: 5 }}`.
Помимо строк, чисел и других выражений JavaScript, вы можете даже передавать объекты в JSX. Объекты также обозначаются фигурными скобками, например `{ name: "Hedy Lamarr", inventions: 5 }`. Поэтому, чтобы передать объект JS в JSX, вы должны заключить объект в еще одну пару фигурных скобок: `person={{ name: "Hedy Lamarr", inventions: 5 }}`.

You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you pass an object to the `style` attribute:
Вы можете увидеть это с встроенными стилями CSS в JSX. React не требует использования встроенных стилей (CSS-классы отлично подходят для большинства случаев). Но когда вам нужен встроенный стиль, вы передаете объект атрибуту `style`:

<Sandpack>

Expand All @@ -148,9 +148,9 @@ ul { padding: 20px 20px 20px 40px; margin: 0; }

</Sandpack>

Try changing the values of `backgroundColor` and `color`.
Попробуйте изменить значения `backgroundColor` и `color`.

You can really see the JavaScript object inside the curly braces when you write it like this:
Вы действительно можете увидеть объект JavaScript внутри фигурных скобок, когда пишете его так:

```js {2-5}
<ul style={
Expand All @@ -161,17 +161,17 @@ You can really see the JavaScript object inside the curly braces when you write
}>
```

The next time you see `{{` and `}}` in JSX, know that it's nothing more than an object inside the JSX curlies!
В следующий раз, когда вы увидите `{{` и `}}` в JSX, знайте, что это не более чем объект внутри фигурных скобок JSX!

<Pitfall>

Inline `style` properties are written in camelCase. For example, HTML `<ul style="background-color: black">` would be written as `<ul style={{ backgroundColor: 'black' }}>` in your component.
Свойства встроенного `style` пишутся в camelCase. Например, HTML `<ul style="background-color: black">` будет записан как `<ul style={{ backgroundColor: 'black' }}>` в вашем компоненте.

</Pitfall>

## More fun with JavaScript objects and curly braces {/*more-fun-with-javascript-objects-and-curly-braces*/}
## Больше возможностей с объектами JavaScript и фигурными скобками {/*more-fun-with-javascript-objects-and-curly-braces*/}

You can move several expressions into one object, and reference them in your JSX inside curly braces:
Вы можете объединить несколько выражений в один объект и ссылаться на них в вашем JSX внутри фигурных скобок:

<Sandpack>

Expand Down Expand Up @@ -211,7 +211,7 @@ body > div > div { padding: 20px; }

</Sandpack>

In this example, the `person` JavaScript object contains a `name` string and a `theme` object:
В этом примере объект JavaScript `person` содержит строку `name` и объект `theme`:

```js
const person = {
Expand All @@ -223,31 +223,31 @@ const person = {
};
```

The component can use these values from `person` like so:
Компонент может использовать эти значения из `person` следующим образом:

```js
<div style={person.theme}>
<h1>{person.name}'s Todos</h1>
```

JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.
JSX очень минималистичен как язык шаблонов, потому что он позволяет организовывать данные и логику с помощью JavaScript.

<Recap>

Now you know almost everything about JSX:
Теперь вы знаете почти все о JSX:

* JSX attributes inside quotes are passed as strings.
* Curly braces let you bring JavaScript logic and variables into your markup.
* They work inside the JSX tag content or immediately after `=` in attributes.
* `{{` and `}}` is not special syntax: it's a JavaScript object tucked inside JSX curly braces.
* Атрибуты JSX в кавычках передаются как строки.
* Фигурные скобки позволяют вставлять логику и переменные JavaScript в вашу разметку.
* Они работают внутри содержимого JSX-тега или сразу после `=` в атрибутах.
* `{{` и `}}` — это не специальный синтаксис: это объект JavaScript, помещенный внутрь фигурных скобок JSX.

</Recap>

<Challenges>

#### Fix the mistake {/*fix-the-mistake*/}
#### Исправьте ошибку {/*fix-the-mistake*/}

This code crashes with an error saying `Objects are not valid as a React child`:
Этот код выдает ошибку `Objects are not valid as a React child`:

<Sandpack>

Expand Down Expand Up @@ -287,15 +287,15 @@ body > div > div { padding: 20px; }

</Sandpack>

Can you find the problem?
Можете ли вы найти проблему?

<Hint>Look for what's inside the curly braces. Are we putting the right thing there?</Hint>
<Hint>Посмотрите, что находится внутри фигурных скобок. Правильное ли мы туда поместили?</Hint>

<Solution>

This is happening because this example renders *an object itself* into the markup rather than a string: `<h1>{person}'s Todos</h1>` is trying to render the entire `person` object! Including raw objects as text content throws an error because React doesn't know how you want to display them.
Это происходит потому, что в этом примере *сам объект* рендерится в разметку, а не строка: `<h1>{person}'s Todos</h1>` пытается отрендерить весь объект `person`! Включение необработанных объектов в качестве текстового содержимого вызывает ошибку, потому что React не знает, как вы хотите их отобразить.

To fix it, replace `<h1>{person}'s Todos</h1>` with `<h1>{person.name}'s Todos</h1>`:
Чтобы исправить это, замените `<h1>{person}'s Todos</h1>` на `<h1>{person.name}'s Todos</h1>`:

<Sandpack>

Expand Down Expand Up @@ -337,9 +337,9 @@ body > div > div { padding: 20px; }

</Solution>

#### Extract information into an object {/*extract-information-into-an-object*/}
#### Извлеките информацию в объект {/*extract-information-into-an-object*/}

Extract the image URL into the `person` object.
Извлеките URL изображения в объект `person`.

<Sandpack>

Expand Down Expand Up @@ -381,7 +381,7 @@ body > div > div { padding: 20px; }

<Solution>

Move the image URL into a property called `person.imageUrl` and read it from the `<img>` tag using the curlies:
Переместите URL изображения в свойство `person.imageUrl` и считайте его из тега `<img>`, используя фигурные скобки:

<Sandpack>

Expand Down Expand Up @@ -424,13 +424,13 @@ body > div > div { padding: 20px; }

</Solution>

#### Write an expression inside JSX curly braces {/*write-an-expression-inside-jsx-curly-braces*/}
#### Напишите выражение внутри фигурных скобок JSX {/*write-an-expression-inside-jsx-curly-braces*/}

In the object below, the full image URL is split into four parts: base URL, `imageId`, `imageSize`, and file extension.
В приведенном ниже объекте полный URL изображения разделен на четыре части: базовый URL, `imageId`, `imageSize` и расширение файла.

We want the image URL to combine these attributes together: base URL (always `'https://i.imgur.com/'`), `imageId` (`'7vQD0fP'`), `imageSize` (`'s'`), and file extension (always `'.jpg'`). However, something is wrong with how the `<img>` tag specifies its `src`.
Мы хотим, чтобы URL изображения объединял эти атрибуты: базовый URL (всегда `'https://i.imgur.com/'`), `imageId` (`'7vQD0fP'`), `imageSize` (`'s'`) и расширение файла (всегда `'.jpg'`). Однако в том, как тег `<img>` указывает свой `src`, есть ошибка.

Can you fix it?
Можете ли вы это исправить?

<Sandpack>

Expand Down Expand Up @@ -474,15 +474,15 @@ body > div > div { padding: 20px; }

</Sandpack>

To check that your fix worked, try changing the value of `imageSize` to `'b'`. The image should resize after your edit.
Чтобы проверить, сработал ли ваш фикс, попробуйте изменить значение `imageSize` на `'b'`. Изображение должно измениться в размере после вашего редактирования.

<Solution>

You can write it as `src={baseUrl + person.imageId + person.imageSize + '.jpg'}`.
Вы можете написать это как `src={baseUrl + person.imageId + person.imageSize + '.jpg'}`.

1. `{` opens the JavaScript expression
2. `baseUrl + person.imageId + person.imageSize + '.jpg'` produces the correct URL string
3. `}` closes the JavaScript expression
1. `{` открывает выражение JavaScript
2. `baseUrl + person.imageId + person.imageSize + '.jpg'` создает правильную строку URL
3. `}` закрывает выражение JavaScript

<Sandpack>

Expand Down Expand Up @@ -525,7 +525,7 @@ body > div > div { padding: 20px; }

</Sandpack>

You can also move this expression into a separate function like `getImageUrl` below:
Вы также можете вынести это выражение в отдельную функцию, как `getImageUrl` ниже:

<Sandpack>

Expand Down Expand Up @@ -580,8 +580,8 @@ body > div > div { padding: 20px; }

</Sandpack>

Variables and functions can help you keep the markup simple!
Переменные и функции могут помочь вам сохранить разметку простой!

</Solution>

</Challenges>
</Challenges>
Loading