`:](/reference/react/Fragment#rendering-a-list-of-fragments)
```js
import { Fragment } from 'react';
@@ -393,46 +394,47 @@ const listItems = people.map(person =>
);
```
-Fragments disappear from the DOM, so this will produce a flat list of ``, `
`, `
`, `
`, and so on.
+Фрагменты исчезают из DOM, поэтому это приведет к плоскому списку элементов `
`, `
`, `
`, `
`, и т.д.
-### Where to get your `key` {/*where-to-get-your-key*/}
+### Откуда взять ключ {/*where-to-get-your-key*/}
+
+Разные источники данных предоставляют разные источники для ключей:
-Different sources of data provide different sources of keys:
+* **Данные из базы данных:** Если ваши данные приходят с базы данных, то вы можете использовать ключи/ID с базы данных, которые по своей природе уникальны.
-* **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
-* **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items.
+* **Локальные данные:** Если ваши данные генерируются и хранятся локально (к примеру, заметки в приложении для ведений заметок), используйте инкрементный счетчик, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) или пакет [`uuid`](https://www.npmjs.com/package/uuid) при создании элементов.
-### Rules of keys {/*rules-of-keys*/}
+### Правила ключей {/*rules-of-keys*/}
-* **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays.
-* **Keys must not change** or that defeats their purpose! Don't generate them while rendering.
+* **Ключи должны быть уникальны среди своих соседних элементов.** Однако, можно использовать одинаковые ключи для JSX-узлов в _разных_ массивах.
+* **Ключи не должны меняться**, так как это лишает их смысла! Не генерируйте их во время рендеринга.
-### Why does React need keys? {/*why-does-react-need-keys*/}
+### Почему React нужны ключи? {/*why-does-react-need-keys*/}
-Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.
+Представьте что у файлов на вашем рабочем столе не было бы имен. Взамен, вы бы ссылались на них по их порядку -- первый файл, второй файл, и т.д. Возможно к этому и можно привыкнуть, но когда вы удалите какой-либо файл, порядок изменится и все станет запутанным. Второй файл станет первым, третий файл станет вторым, и т. д.
-File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the _position_ changes due to reordering, the `key` lets React identify the item throughout its lifetime.
+Названия файлов в папке и JSX ключи в массиве имеют схожую цель. Они позволяют нам отличать элементы от их других элементов в массиве. А хорошо выбранный ключ предоставляет больше информации, чем позиция в массиве. Даже если _позиция_ изменится из-за смены порядка, `key` позволит React идентифицировать элемент на протяжении всего существования элемента.
-You might be tempted to use an item's index in the array as its key. In fact, that's what React will use if you don't specify a `key` at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
+Возможно вам захочется использовать индекс элемента в массиве в качестве ключа. В действительности, это то, что React будет использовать, если вы не укажете `key`. Но порядок, в котором вы рендерите элементы, может поменяться со временем, если какой-либо элемент будет вставлен, удален или если массив будет переупорядочен. Индекс в качестве ключа часто приводит к коварным и сбивающим с толку ошибкам.
-Similarly, do not generate keys on the fly, e.g. with `key={Math.random()}`. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data.
+Аналогично, не генерируйте ключи на лету, например, с помощью `key={Math.random()}`. Это приведет к тому, что ключи никогда не будут совпадать между рендерами, что приведет к пересозданию всех ваших компонентов и DOM при каждом рендере. Это не только медленно, но также приведет к потере любых данных введённых пользователем внутри элементов списка. Вместо этого используйте стабильный ID, основанный на данных.
-Note that your components won't receive `key` as a prop. It's only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: ``.
+Заметьте, что ваши компоненты не получат `key` в качестве пропа. Он используется только как подсказка для React. Если ваш компонент нуждается в ID, вы должны передать его как отдельный проп: ``..
-On this page you learned:
+На этой странице вы узнали:
-* How to move data out of components and into data structures like arrays and objects.
-* How to generate sets of similar components with JavaScript's `map()`.
-* How to create arrays of filtered items with JavaScript's `filter()`.
-* Why and how to set `key` on each component in a collection so React can keep track of each of them even if their position or data changes.
+* Как перенести данные из компонентов в структуры данных, такие как массивы и объекты.
+* Как создавать коллекции схожих компонентов с помощью JavaScript `map()`.
+* Как создавать массивы отфильтрованных элементов с помощью JavaScript `filter()`.
+* Зачем и как присваивать ключ каждому компоненту в коллекции, чтобы React мог отслеживать изменения каждого из них.
@@ -440,11 +442,11 @@ On this page you learned:
-#### Splitting a list in two {/*splitting-a-list-in-two*/}
+#### Разделение списка на два {/*splitting-a-list-in-two*/}
-This example shows a list of all people.
+Этот пример показывает список всех людей в `people`.
-Change it to show two separate lists one after another: **Chemists** and **Everyone Else.** Like previously, you can determine whether a person is a chemist by checking if `person.profession === 'chemist'`.
+Поменяйте код так, чтобы он показывал два списка один за другим: **Химики** и **Все остальные**. Как и раньше, вы можете определить, является ли человек химиком, проверив `person.profession === 'химик'`.
@@ -461,14 +463,14 @@ export default function List() {
/>
{person.name}:
- {' ' + person.profession + ' '}
- known for {person.accomplishment}
+ {' ' + person.profession}.
+ Достижение: {person.accomplishment}
);
return (
- Scientists
+ Ученые
);
@@ -478,33 +480,33 @@ export default function List() {
```js data.js
export const people = [{
id: 0,
- name: 'Creola Katherine Johnson',
- profession: 'mathematician',
- accomplishment: 'spaceflight calculations',
+ name: 'Креола Кэтрин Джонсон (Creola Katherine Johnson)',
+ profession: 'математик',
+ accomplishment: 'расчёты для космических полетов',
imageId: 'MK3eW3A'
}, {
id: 1,
- name: 'Mario José Molina-Pasquel Henríquez',
- profession: 'chemist',
- accomplishment: 'discovery of Arctic ozone hole',
+ name: 'Марио Молина (Mario José Molina-Pasquel Henríquez)',
+ profession: 'химик',
+ accomplishment: 'обнаружение дыр в озоновом слое',
imageId: 'mynHUSa'
}, {
id: 2,
- name: 'Mohammad Abdus Salam',
- profession: 'physicist',
- accomplishment: 'electromagnetism theory',
+ name: 'Мухаммад Абдус Салам (Mohammad Abdus Salam)',
+ profession: 'физик',
+ accomplishment: 'открытие теории электромагнетизма',
imageId: 'bE7W1ji'
}, {
id: 3,
- name: 'Percy Lavon Julian',
- profession: 'chemist',
- accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
+ name: 'Перси Джулиан (Percy Lavon Julian)',
+ profession: 'химик',
+ accomplishment: 'изобретение препаратов с кортизоном, стероидов и противозачаточных таблеток',
imageId: 'IOjWm71'
}, {
id: 4,
- name: 'Subrahmanyan Chandrasekhar',
- profession: 'astrophysicist',
- accomplishment: 'white dwarf star mass calculations',
+ name: 'Субраманьян Чандрасекар (Subrahmanyan Chandrasekhar)',
+ profession: 'астрофизик',
+ accomplishment: 'расчёт массы белого карлика',
imageId: 'lrWQx8l'
}];
```
@@ -535,7 +537,7 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-You could use `filter()` twice, creating two separate arrays, and then `map` over both of them:
+Вы можете использовать `filter()` дважды, создав два отдельных массива, а затем использовать `map()` на обоих:
@@ -545,15 +547,15 @@ import { getImageUrl } from './utils.js';
export default function List() {
const chemists = people.filter(person =>
- person.profession === 'chemist'
+ person.profession === 'химик'
);
const everyoneElse = people.filter(person =>
- person.profession !== 'chemist'
+ person.profession !== 'химик'
);
return (
- Scientists
- Chemists
+ Ученые
+ Химики
- Everyone Else
+ Все остальные
-In this solution, the `map` calls are placed directly inline into the parent `` elements, but you could introduce variables for them if you find that more readable.
+В данном решении, вызовы `map` помещены непосредственно в родительские элементы ``, но вы можете вынести их в отдельные переменные, если cчитаете это более читабельным.
-There is still a bit duplication between the rendered lists. You can go further and extract the repetitive parts into a `` component:
+Между отображаемыми списками все еще существует небольшое дублирование. Вы можете пойти дальше и извлечь повторяющиеся части в компонент ``:
@@ -671,8 +673,8 @@ function ListSection({ title, people }) {
/>
{person.name}:
- {' ' + person.profession + ' '}
- known for {person.accomplishment}
+ {' ' + person.profession}.
+ Достижение: {person.accomplishment}
)}
@@ -683,20 +685,20 @@ function ListSection({ title, people }) {
export default function List() {
const chemists = people.filter(person =>
- person.profession === 'chemist'
+ person.profession === 'химик'
);
const everyoneElse = people.filter(person =>
- person.profession !== 'chemist'
+ person.profession !== 'химик'
);
return (
Scientists
@@ -707,33 +709,33 @@ export default function List() {
```js data.js
export const people = [{
id: 0,
- name: 'Creola Katherine Johnson',
- profession: 'mathematician',
- accomplishment: 'spaceflight calculations',
+ name: 'Креола Кэтрин Джонсон (Creola Katherine Johnson)',
+ profession: 'математик',
+ accomplishment: 'расчёты для космических полетов',
imageId: 'MK3eW3A'
}, {
id: 1,
- name: 'Mario José Molina-Pasquel Henríquez',
- profession: 'chemist',
- accomplishment: 'discovery of Arctic ozone hole',
+ name: 'Марио Молина (Mario José Molina-Pasquel Henríquez)',
+ profession: 'химик',
+ accomplishment: 'обнаружение дыр в озоновом слое',
imageId: 'mynHUSa'
}, {
id: 2,
- name: 'Mohammad Abdus Salam',
- profession: 'physicist',
- accomplishment: 'electromagnetism theory',
+ name: 'Мухаммад Абдус Салам (Mohammad Abdus Salam)',
+ profession: 'физик',
+ accomplishment: 'открытие теории электромагнетизма',
imageId: 'bE7W1ji'
}, {
id: 3,
- name: 'Percy Lavon Julian',
- profession: 'chemist',
- accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
+ name: 'Перси Джулиан (Percy Lavon Julian)',
+ profession: 'химик',
+ accomplishment: 'изобретение препаратов с кортизоном, стероидов и противозачаточных таблеток',
imageId: 'IOjWm71'
}, {
id: 4,
- name: 'Subrahmanyan Chandrasekhar',
- profession: 'astrophysicist',
- accomplishment: 'white dwarf star mass calculations',
+ name: 'Субраманьян Чандрасекар (Subrahmanyan Chandrasekhar)',
+ profession: 'астрофизик',
+ accomplishment: 'расчёт массы белого карлика',
imageId: 'lrWQx8l'
}];
```
@@ -762,9 +764,9 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-A very attentive reader might notice that with two `filter` calls, we check each person's profession twice. Checking a property is very fast, so in this example it's fine. If your logic was more expensive than that, you could replace the `filter` calls with a loop that manually constructs the arrays and checks each person once.
+Очень внимательный читатель мог бы заметить, что при двух вызовах `filter` мы дважды проверяем профессию каждого человека. Проверка свойства происходит очень быстро, поэтому в данном примере это нормально. Если бы ваша логика была более затратна, вы могли бы заменить вызовы `filter` на цикл, который вручную создает массивы и проверяет каждого человека один раз.
-In fact, if `people` never change, you could move this code out of your component. From React's perspective, all that matters is that you give it an array of JSX nodes in the end. It doesn't care how you produce that array:
+К тому же, если `people` никогда не меняется, вы можете вынести этот код из вашего компонента. С точки зрения React, единственное что имеет значение, это то, что вы предоставляете массив JSX-узлов в конце. React не важно, как вы создаете этот массив:
@@ -775,7 +777,7 @@ import { getImageUrl } from './utils.js';
let chemists = [];
let everyoneElse = [];
people.forEach(person => {
- if (person.profession === 'chemist') {
+ if (person.profession === 'химик') {
chemists.push(person);
} else {
everyoneElse.push(person);
@@ -795,8 +797,8 @@ function ListSection({ title, people }) {
/>
{person.name}:
- {' ' + person.profession + ' '}
- known for {person.accomplishment}
+ {' ' + person.profession}.
+ Достижение: {person.accomplishment}
)}
@@ -810,11 +812,11 @@ export default function List() {
Scientists
@@ -825,33 +827,33 @@ export default function List() {
```js data.js
export const people = [{
id: 0,
- name: 'Creola Katherine Johnson',
- profession: 'mathematician',
- accomplishment: 'spaceflight calculations',
+ name: 'Креола Кэтрин Джонсон (Creola Katherine Johnson)',
+ profession: 'математик',
+ accomplishment: 'расчёты для космических полетов',
imageId: 'MK3eW3A'
}, {
id: 1,
- name: 'Mario José Molina-Pasquel Henríquez',
- profession: 'chemist',
- accomplishment: 'discovery of Arctic ozone hole',
+ name: 'Марио Молина (Mario José Molina-Pasquel Henríquez)',
+ profession: 'химик',
+ accomplishment: 'обнаружение дыр в озоновом слое',
imageId: 'mynHUSa'
}, {
id: 2,
- name: 'Mohammad Abdus Salam',
- profession: 'physicist',
- accomplishment: 'electromagnetism theory',
+ name: 'Мухаммад Абдус Салам (Mohammad Abdus Salam)',
+ profession: 'физик',
+ accomplishment: 'открытие теории электромагнетизма',
imageId: 'bE7W1ji'
}, {
id: 3,
- name: 'Percy Lavon Julian',
- profession: 'chemist',
- accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
+ name: 'Перси Джулиан (Percy Lavon Julian)',
+ profession: 'химик',
+ accomplishment: 'изобретение препаратов с кортизоном, стероидов и противозачаточных таблеток',
imageId: 'IOjWm71'
}, {
id: 4,
- name: 'Subrahmanyan Chandrasekhar',
- profession: 'astrophysicist',
- accomplishment: 'white dwarf star mass calculations',
+ name: 'Субраманьян Чандрасекар (Subrahmanyan Chandrasekhar)',
+ profession: 'астрофизик',
+ accomplishment: 'расчёт массы белого карлика',
imageId: 'lrWQx8l'
}];
```
@@ -882,13 +884,13 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-#### Nested lists in one component {/*nested-lists-in-one-component*/}
+#### Вложенные списки в одном компоненте {/*nested-lists-in-one-component*/}
-Make a list of recipes from this array! For each recipe in the array, display its name as an `` and list its ingredients in a ``.
+Создайте список рецептов из данного массива! Для каждого рецепта в массиве отобразите название внутри `` и перечислите ингредиенты в ``.
-This will require nesting two different `map` calls.
+Для этого потребуется вложение двух разных вызовов `map`.
@@ -900,7 +902,7 @@ import { recipes } from './data.js';
export default function RecipeList() {
return (
-
Recipes
+ Рецепты
);
}
@@ -909,16 +911,16 @@ export default function RecipeList() {
```js data.js
export const recipes = [{
id: 'greek-salad',
- name: 'Greek Salad',
- ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
+ name: 'Греческий салат',
+ ingredients: ['помидоры', 'огурец', 'лук', 'оливки', 'сыр фета']
}, {
id: 'hawaiian-pizza',
- name: 'Hawaiian Pizza',
- ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
+ name: 'Гавайская пицца',
+ ingredients: ['тесто для пиццы', 'соус для пиццы', 'моцарелла', 'ветчина', 'ананас']
}, {
id: 'hummus',
- name: 'Hummus',
- ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
+ name: 'Хумус',
+ ingredients: ['нут', 'оливковое масло', 'зубчики чеснока', 'лимон', 'тахини']
}];
```
@@ -926,7 +928,7 @@ export const recipes = [{
-Here is one way you could go about it:
+Вот один из способов, как вы можете это сделать:
@@ -936,7 +938,7 @@ import { recipes } from './data.js';
export default function RecipeList() {
return (
-
Recipes
+
Рецепты
{recipes.map(recipe =>
{recipe.name}
@@ -957,28 +959,28 @@ export default function RecipeList() {
```js data.js
export const recipes = [{
id: 'greek-salad',
- name: 'Greek Salad',
- ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
+ name: 'Греческий салат',
+ ingredients: ['помидоры', 'огурец', 'лук', 'оливки', 'сыр фета']
}, {
id: 'hawaiian-pizza',
- name: 'Hawaiian Pizza',
- ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
+ name: 'Гавайская пицца',
+ ingredients: ['тесто для пиццы', 'соус для пиццы', 'моцарелла', 'ветчина', 'ананас']
}, {
id: 'hummus',
- name: 'Hummus',
- ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
+ name: 'Хумус',
+ ingredients: ['нут', 'оливковое масло', 'зубчики чеснока', 'лимон', 'тахини']
}];
```
-Each of the `recipes` already includes an `id` field, so that's what the outer loop uses for its `key`. There is no ID you could use to loop over ingredients. However, it's reasonable to assume that the same ingredient won't be listed twice within the same recipe, so its name can serve as a `key`. Alternatively, you could change the data structure to add IDs, or use index as a `key` (with the caveat that you can't safely reorder ingredients).
+Каждый из рецептов уже содержит поле `id`, поэтому это и используется внешним циклом в качестве ключа. Нет ID, который можно было бы использовать для перебора ингредиентов. Однако разумно предположить, что один и тот же ингредиент не будет перечислен дважды в одном рецепте, поэтому его имя может служить в качестве ключа. Как вариант, вы можете изменить структуру данных, чтобы добавить ID, или же использовать индекс в качестве ключа (с оговоркой, что вы не можете безопасно изменять порядок ингредиентов).
-#### Extracting a list item component {/*extracting-a-list-item-component*/}
+#### Извлечение компонента элемента списка {/*extracting-a-list-item-component*/}
-This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why?
+Компонент `RecipeList` содержит два вложенных вызова `map`. Чтобы упростить его, извлеките компонент `Recipe`, который будет принимать пропсы `id`, `name` и `ingredients`. Где вы разместите внешний `key` и почему?
@@ -988,7 +990,7 @@ import { recipes } from './data.js';
export default function RecipeList() {
return (
-
Recipes
+
Рецепты
{recipes.map(recipe =>
{recipe.name}
@@ -1009,16 +1011,16 @@ export default function RecipeList() {
```js data.js
export const recipes = [{
id: 'greek-salad',
- name: 'Greek Salad',
- ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
+ name: 'Греческий салат',
+ ingredients: ['помидоры', 'огурец', 'лук', 'оливки', 'сыр фета']
}, {
id: 'hawaiian-pizza',
- name: 'Hawaiian Pizza',
- ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
+ name: 'Гавайская пицца',
+ ingredients: ['тесто для пиццы', 'соус для пиццы', 'моцарелла', 'ветчина', 'ананас']
}, {
id: 'hummus',
- name: 'Hummus',
- ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
+ name: 'Хумус',
+ ingredients: ['нут', 'оливковое масло', 'зубчики чеснока', 'лимон', 'тахини']
}];
```
@@ -1026,7 +1028,7 @@ export const recipes = [{
-You can copy-paste the JSX from the outer `map` into a new `Recipe` component and return that JSX. Then you can change `recipe.name` to `name`, `recipe.id` to `id`, and so on, and pass them as props to the `Recipe`:
+Вы можете скопировать и вставить JSX из внешнего вызова map в новый компонент `Recipe` и вернуть этот JSX. Затем вы можете изменить `recipe.name` на `name`, `recipe.id` на `id` и т.д., и передать их в виде пропсов компоненту `Recipe`:
@@ -1051,7 +1053,7 @@ function Recipe({ id, name, ingredients }) {
export default function RecipeList() {
return (
-
Recipes
+
Рецепты
{recipes.map(recipe =>
)}
@@ -1063,51 +1065,51 @@ export default function RecipeList() {
```js data.js
export const recipes = [{
id: 'greek-salad',
- name: 'Greek Salad',
- ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
+ name: 'Греческий салат',
+ ingredients: ['помидоры', 'огурец', 'лук', 'оливки', 'сыр фета']
}, {
id: 'hawaiian-pizza',
- name: 'Hawaiian Pizza',
- ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
+ name: 'Гавайская пицца',
+ ingredients: ['тесто для пиццы', 'соус для пиццы', 'моцарелла', 'ветчина', 'ананас']
}, {
id: 'hummus',
- name: 'Hummus',
- ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
+ name: 'Хумус',
+ ingredients: ['нут', 'оливковое масло', 'зубчики чеснока', 'лимон', 'тахини']
}];
```
-Here, `
` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: `
`.
+Здесь `
` -- это сокращенный синтаксис, означающий "передайте все свойства объекта `recipe` как пропсы в компонент `Recipe`". Вы также можете явно задать каждый проп: `
`.
-**Note that the `key` is specified on the `
` itself rather than on the root `` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of `
`s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste.
+**Обратите внимание, что `key` указывается на самом компоненте ``, а не на корневом ``, возвращаемом из `Recipe`.** Всё потому, что этот `key` необходим непосредственно в контексте окружающего массива. Ранее у вас был массив `
`, поэтому каждому из них требовался ключ, но теперь у вас есть массив `
`. Другими словами, когда вы извлекаете компонент, не забудьте оставить ключ за пределами JSX, который вы копируете и вставляете.
-#### List with a separator {/*list-with-a-separator*/}
+#### Список с разделителем {/*list-with-a-separator*/}
-This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `` tag. Your job is to insert an `
` separator between each paragraph. Your resulting structure should look like this:
+Данный пример рендерит известное хокку Кацусики Хокусая, каждая строка обернута в тег ``. Ваша задача -- вставить разделитель `
` между каждым параграфом. Ваша структура должна выглядеть так:
```js
- I write, erase, rewrite
+ Я пишу, стираю, переписываю,
- Erase again, and then
+ Снова стереть, а затем
- A poppy blooms.
+ Цветет мак.
```
-A haiku only contains three lines, but your solution should work with any number of lines. Note that `
` elements only appear *between* the `` elements, not in the beginning or the end!
+Хокку содержит только три строки, но ваше решение должно работать с любым количеством строк. Обратите внимание, что элементы `
` должны быть *между* элементами ``, а не в начале или в конце!
```js
const poem = {
lines: [
- 'I write, erase, rewrite',
- 'Erase again, and then',
- 'A poppy blooms.'
+ 'Я пишу, стираю, переписываю,',
+ 'Снова стереть, а затем',
+ 'Цветет мак.'
]
};
@@ -1141,33 +1143,33 @@ hr {
-(This is a rare case where index as a key is acceptable because a poem's lines will never reorder.)
+(Это один из редких случаев когда можно использовать индекс в качестве ключа, потому что строки стихотворения никогда не будут переупорядочиваться.)
-You'll either need to convert `map` to a manual loop, or use a fragment.
+Вам понадобится либо поменять `map` на обычный цикл, либо использовать фрагмент.
-You can write a manual loop, inserting `
` and `...
` into the output array as you go:
+Вы можете использовать обычный цикл, вставляя `
` и `...
` в массив для вывода по мере выполнения:
```js
const poem = {
lines: [
- 'I write, erase, rewrite',
- 'Erase again, and then',
- 'A poppy blooms.'
+ 'Я пишу, стираю, переписываю,',
+ 'Снова стереть, а затем',
+ 'Цветет мак.'
]
};
export default function Poem() {
let output = [];
- // Fill the output array
+ // Заполнение массива для вывода
poem.lines.forEach((line, i) => {
output.push(
@@ -1178,7 +1180,7 @@ export default function Poem() {
);
});
- // Remove the first
+ // Убираем первый
output.shift();
return (
@@ -1206,9 +1208,9 @@ hr {
-Using the original line index as a `key` doesn't work anymore because each separator and paragraph are now in the same array. However, you can give each of them a distinct key using a suffix, e.g. `key={i + '-text'}`.
+Использование исходного индекса строки в качестве ключа больше не работает, потому что теперь каждый разделитель и абзац находятся в одном и том же массиве. Однако вы можете присвоить каждому из них уникальный ключ с использованием суффикса, например, `key={i + '-text'}`.
-Alternatively, you could render a collection of fragments which contain `
` and `...
`. However, the `<>...>` shorthand syntax doesn't support passing keys, so you'd have to write `` explicitly:
+В качестве альтернативы, вы можете отрендерить коллекцию фрагментов, содержащих `
` и `...
`. Однако сокращенный синтаксис `<>...>` не поддерживает передачу ключей, поэтому вам придется явно использовать ``:
@@ -1217,9 +1219,9 @@ import { Fragment } from 'react';
const poem = {
lines: [
- 'I write, erase, rewrite',
- 'Erase again, and then',
- 'A poppy blooms.'
+ 'Я пишу, стираю, переписываю,',
+ 'Снова стереть, а затем',
+ 'Цветет мак.'
]
};
@@ -1254,7 +1256,7 @@ hr {
-Remember, fragments (often written as `<> >`) let you group JSX nodes without adding extra ``s!
+Запомните, фрагменты (часто записываемые как `<> >`) позволяют группировать JSX-узлы без добавления дополнительных `
`!