From ee46466156392ed1f9255fab17c7aa719c0d0ec6 Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Wed, 4 Feb 2026 15:03:56 +0000 Subject: [PATCH 1/2] =?UTF-8?q?docs:=20translate=20`describing-the-ui.md`?= =?UTF-8?q?=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/content/learn/describing-the-ui.md | 442 ++----------------------- 1 file changed, 35 insertions(+), 407 deletions(-) diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index 34ee0c01a1..cb8f778a91 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -1,30 +1,30 @@ --- -title: Describing the UI +title: Описание пользовательского интерфейса --- -React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable *components.* From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you'll learn to create, customize, and conditionally display React components. +React — это JavaScript-библиотека для создания пользовательских интерфейсов (UI). UI состоит из небольших частей, таких как кнопки, текст и изображения. React позволяет объединять их в многократно используемые, вложенные *компоненты*. От веб-сайтов до мобильных приложений — всё на экране можно разбить на компоненты. В этой главе вы научитесь создавать, настраивать и условно отображать компоненты React. -* [How to write your first React component](/learn/your-first-component) -* [When and how to create multi-component files](/learn/importing-and-exporting-components) -* [How to add markup to JavaScript with JSX](/learn/writing-markup-with-jsx) -* [How to use curly braces with JSX to access JavaScript functionality from your components](/learn/javascript-in-jsx-with-curly-braces) -* [How to configure components with props](/learn/passing-props-to-a-component) -* [How to conditionally render components](/learn/conditional-rendering) -* [How to render multiple components at a time](/learn/rendering-lists) -* [How to avoid confusing bugs by keeping components pure](/learn/keeping-components-pure) -* [Why understanding your UI as trees is useful](/learn/understanding-your-ui-as-a-tree) +* [Как написать свой первый компонент React](/learn/your-first-component) +* [Когда и как создавать файлы с несколькими компонентами](/learn/importing-and-exporting-components) +* [Как добавлять разметку в JavaScript с помощью JSX](/learn/writing-markup-with-jsx) +* [Как использовать фигурные скобки в JSX для доступа к функциональности JavaScript из ваших компонентов](/learn/javascript-in-jsx-with-curly-braces) +* [Как настраивать компоненты с помощью пропсов](/learn/passing-props-to-a-component) +* [Как условно отображать компоненты](/learn/conditional-rendering) +* [Как одновременно отображать несколько компонентов](/learn/rendering-lists) +* [Как избегать запутанных ошибок, сохраняя компоненты чистыми](/learn/keeping-components-pure) +* [Почему полезно рассматривать пользовательский интерфейс как деревья](/learn/understanding-your-ui-as-a-tree) -## Your first component {/*your-first-component*/} +## Ваш первый компонент {/*your-first-component*/} -React applications are built from isolated pieces of UI called *components*. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components: +Приложения React строятся из изолированных частей пользовательского интерфейса, называемых *компонентами*. Компонент React — это функция JavaScript, которую вы можете дополнить разметкой. Компоненты могут быть маленькими, как кнопка, или большими, как целая страница. Вот компонент `Gallery`, отображающий три компонента `Profile`: @@ -58,13 +58,13 @@ img { margin: 0 10px 10px 0; height: 90px; } -Read **[Your First Component](/learn/your-first-component)** to learn how to declare and use React components. +Прочитайте **[Ваш первый компонент](/learn/your-first-component)**, чтобы узнать, как объявлять и использовать компоненты React. -## Importing and exporting components {/*importing-and-exporting-components*/} +## Импорт и экспорт компонентов {/*importing-and-exporting-components*/} -You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can *export* a component into its own file, and then *import* that component from another file: +Вы можете объявлять множество компонентов в одном файле, но большие файлы могут стать трудными для навигации. Чтобы решить эту проблему, вы можете *экспортировать* компонент в собственный файл, а затем *импортировать* этот компонент из другого файла: @@ -113,15 +113,15 @@ img { margin: 0 10px 10px 0; } -Read **[Importing and Exporting Components](/learn/importing-and-exporting-components)** to learn how to split components into their own files. +Прочитайте **[Импорт и экспорт компонентов](/learn/importing-and-exporting-components)**, чтобы узнать, как разделять компоненты на собственные файлы. -## Writing markup with JSX {/*writing-markup-with-jsx*/} +## Написание разметки с помощью JSX {/*writing-markup-with-jsx*/} -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. +Каждый компонент React — это функция JavaScript, которая может содержать некоторую разметку, которую React отображает в браузере. Компоненты React используют расширение синтаксиса под названием JSX для представления этой разметки. JSX очень похож на HTML, но он немного строже и может отображать динамическую информацию. -If we paste existing HTML markup into a React component, it won't always work: +Если мы вставим существующую HTML-разметку в компонент React, это не всегда сработает: @@ -150,413 +150,41 @@ img { height: 90px; } -If you have existing HTML like this, you can fix it using a [converter](https://transform.tools/html-to-jsx): +Если у вас есть существующий - - -```js -export default function TodoList() { - return ( - <> -

Hedy Lamarr's Todos

- Hedy Lamarr -
    -
  • Invent new traffic lights
  • -
  • Rehearse a movie scene
  • -
  • Improve spectrum technology
  • -
- - ); -} -``` - -```css -img { height: 90px; } -``` - -
- - - -Read **[Writing Markup with JSX](/learn/writing-markup-with-jsx)** to learn how to write valid JSX. - - - -## JavaScript in JSX with curly braces {/*javascript-in-jsx-with-curly-braces*/} - -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: - - - -```js -const person = { - name: 'Gregorio Y. Zara', - theme: { - backgroundColor: 'black', - color: 'pink' - } -}; - -export default function TodoList() { - return ( -
-

{person.name}'s Todos

- Gregorio Y. Zara -
    -
  • Improve the videophone
  • -
  • Prepare aeronautics lectures
  • -
  • Work on the alcohol-fuelled engine
  • -
-
- ); -} -``` - -```css -body { padding: 0; margin: 0 } -body > div > div { padding: 20px; } -.avatar { border-radius: 50%; height: 90px; } -``` - -
- - - -Read **[JavaScript in JSX with Curly Braces](/learn/javascript-in-jsx-with-curly-braces)** to learn how to access JavaScript data from JSX. - - - -## Passing props to a component {/*passing-props-to-a-component*/} - -React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX! - - - -```js -import { getImageUrl } from './utils.js' - -export default function Profile() { - return ( - - - - ); -} - -function Avatar({ person, size }) { - return ( - {person.name} - ); -} - -function Card({ children }) { - return ( -
- {children} -
- ); -} - -``` - -```js src/utils.js -export function getImageUrl(person, size = 's') { - return ( - 'https://i.imgur.com/' + - person.imageId + - size + - '.jpg' - ); -} -``` - -```css -.card { - width: fit-content; - margin: 5px; - padding: 5px; - font-size: 20px; - text-align: center; - border: 1px solid #aaa; - border-radius: 20px; - background: #fff; -} -.avatar { - margin: 20px; - border-radius: 50%; -} -``` - -
- - - -Read **[Passing Props to a Component](/learn/passing-props-to-a-component)** to learn how to pass and read props. - - - -## Conditional rendering {/*conditional-rendering*/} - -Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators. - -In this example, the JavaScript `&&` operator is used to conditionally render a checkmark: - - - -```js -function Item({ name, isPacked }) { - return ( -
  • - {name} {isPacked && '✅'} -
  • - ); -} - -export default function PackingList() { - return ( -
    -

    Sally Ride's Packing List

    -
      - - - -
    -
    - ); -} -``` - -
    - - - -Read **[Conditional Rendering](/learn/conditional-rendering)** to learn the different ways to render content conditionally. - - - -## Rendering lists {/*rendering-lists*/} - -You will often want to display multiple similar components from a collection of data. You can use JavaScript's `filter()` and `map()` with React to filter and transform your array of data into an array of components. - -For each array item, you will need to specify a `key`. Usually, you will want to use an ID from the database as a `key`. Keys let React keep track of each item's place in the list even if the list changes. - - - -```js src/App.js -import { people } from './data.js'; -import { getImageUrl } from './utils.js'; - -export default function List() { - const listItems = people.map(person => -
  • - {person.name} -

    - {person.name}: - {' ' + person.profession + ' '} - known for {person.accomplishment} -

    -
  • - ); - return ( -
    -

    Scientists

    -
      {listItems}
    -
    - ); -} -``` - -```js src/data.js -export const people = [{ - id: 0, - name: 'Creola Katherine Johnson', - profession: 'mathematician', - accomplishment: 'spaceflight calculations', - imageId: 'MK3eW3A' -}, { - id: 1, - name: 'Mario José Molina-Pasquel Henríquez', - profession: 'chemist', - accomplishment: 'discovery of Arctic ozone hole', - imageId: 'mynHUSa' -}, { - id: 2, - name: 'Mohammad Abdus Salam', - profession: 'physicist', - accomplishment: 'electromagnetism theory', - imageId: 'bE7W1ji' -}, { - id: 3, - name: 'Percy Lavon Julian', - profession: 'chemist', - accomplishment: 'pioneering cortisone drugs, steroids and birth control pills', - imageId: 'IOjWm71' -}, { - id: 4, - name: 'Subrahmanyan Chandrasekhar', - profession: 'astrophysicist', - accomplishment: 'white dwarf star mass calculations', - imageId: 'lrWQx8l' -}]; -``` - -```js src/utils.js -export function getImageUrl(person) { - return ( - 'https://i.imgur.com/' + - person.imageId + - 's.jpg' - ); -} -``` - -```css -ul { list-style-type: none; padding: 0px 10px; } -li { - margin-bottom: 10px; - display: grid; - grid-template-columns: 1fr 1fr; - align-items: center; -} -img { width: 100px; height: 100px; border-radius: 50%; } -h1 { font-size: 22px; } -h2 { font-size: 20px; } -``` - -
    - - - -Read **[Rendering Lists](/learn/rendering-lists)** to learn how to render a list of components, and how to choose a key. - - - -## Keeping components pure {/*keeping-components-pure*/} - -Some JavaScript functions are *pure.* A pure function: - -* **Minds its own business.** It does not change any objects or variables that existed before it was called. -* **Same inputs, same output.** Given the same inputs, a pure function should always return the same result. - -By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. Here is an example of an impure component: - - - -```js -let guest = 0; - -function Cup() { - // Bad: changing a preexisting variable! - guest = guest + 1; - return

    Tea cup for guest #{guest}

    ; -} - -export default function TeaSet() { - return ( - <> - - - - - ); -} -``` - -
    - -You can make this component pure by passing a prop instead of modifying a preexisting variable: - - - -```js -function Cup({ guest }) { - return

    Tea cup for guest #{guest}

    ; -} - -export default function TeaSet() { - return ( - <> - - - - - ); -} -``` - -
    - - - -Read **[Keeping Components Pure](/learn/keeping-components-pure)** to learn how to write components as pure, predictable functions. - - - -## Your UI as a tree {/*your-ui-as-a-tree*/} +## Ваш UI как дерево {/*your-ui-as-a-tree*/} -React uses trees to model the relationships between components and modules. +React использует деревья для моделирования взаимосвязей между компонентами и модулями. -A React render tree is a representation of the parent and child relationship between components. +Дерево рендеринга React — это представление родительско-дочерних отношений между компонентами. - + -An example React render tree. +Пример дерева рендеринга React. -Components near the top of the tree, near the root component, are considered top-level components. Components with no child components are leaf components. This categorization of components is useful for understanding data flow and rendering performance. +Компоненты, расположенные ближе к вершине дерева, рядом с корневым компонентом, считаются компонентами верхнего уровня. Компоненты без дочерних компонентов являются листовыми компонентами. Такая категоризация компонентов полезна для понимания потока данных и производительности рендеринга. -Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree. +Моделирование взаимосвязей между JavaScript-модулями — ещё один полезный способ понять ваше приложение. Мы называем это деревом зависимостей модулей. - + -An example module dependency tree. +Пример дерева зависимостей модулей. -A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues. +Дерево зависимостей часто используется инструментами сборки для объединения всего необходимого JavaScript-кода, который клиент должен скачать и отрисовать. Большой размер бандла ухудшает пользовательский опыт в React-приложениях. Понимание дерева зависимостей модулей помогает отлаживать такие проблемы. -Read **[Your UI as a Tree](/learn/understanding-your-ui-as-a-tree)** to learn how to create a render and module dependency trees for a React app and how they're useful mental models for improving user experience and performance. +Прочтите **[Ваш UI как дерево](/learn/understanding-your-ui-as-a-tree)**, чтобы узнать, как создавать деревья рендеринга и зависимостей модулей для React-приложения и как они являются полезными ментальными моделями для улучшения пользовательского опыта и производительности. -## What's next? {/*whats-next*/} +## Что дальше? {/*whats-next*/} -Head over to [Your First Component](/learn/your-first-component) to start reading this chapter page by page! +Перейдите к [Ваш первый компонент](/learn/your-first-component), чтобы начать читать эту главу по страницам! -Or, if you're already familiar with these topics, why not read about [Adding Interactivity](/learn/adding-interactivity)? +Или, если вы уже знакомы с этими темами, почему бы не прочитать о [Добавлении интерактивности](/learn/adding-interactivity)? \ No newline at end of file From d0dbafcf031d7a3b9ba5a03ddfbb2bd8d7d10e24 Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Mon, 18 May 2026 16:10:42 +0000 Subject: [PATCH 2/2] =?UTF-8?q?docs:=20translate=20`describing-the-ui.md`?= =?UTF-8?q?=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/content/learn/describing-the-ui.md | 402 ++++++++++++++++++++++++- 1 file changed, 386 insertions(+), 16 deletions(-) diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index cb8f778a91..85cf31de02 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -1,10 +1,9 @@ --- title: Описание пользовательского интерфейса --- - -React — это JavaScript-библиотека для создания пользовательских интерфейсов (UI). UI состоит из небольших частей, таких как кнопки, текст и изображения. React позволяет объединять их в многократно используемые, вложенные *компоненты*. От веб-сайтов до мобильных приложений — всё на экране можно разбить на компоненты. В этой главе вы научитесь создавать, настраивать и условно отображать компоненты React. +React — это JavaScript-библиотека для создания пользовательских интерфейсов (UI). Пользовательские интерфейсы строятся из небольших частей, таких как кнопки, текст и изображения. React позволяет объединять их в многократно используемые, вложенные *компоненты*. От веб-сайтов до мобильных приложений — всё на экране можно разбить на компоненты. В этой главе вы научитесь создавать, настраивать и условно отображать компоненты React. @@ -18,13 +17,13 @@ React — это JavaScript-библиотека для создания пол * [Как условно отображать компоненты](/learn/conditional-rendering) * [Как одновременно отображать несколько компонентов](/learn/rendering-lists) * [Как избегать запутанных ошибок, сохраняя компоненты чистыми](/learn/keeping-components-pure) -* [Почему полезно рассматривать пользовательский интерфейс как деревья](/learn/understanding-your-ui-as-a-tree) +* [Почему полезно понимать свой UI как деревья](/learn/understanding-your-ui-as-a-tree) ## Ваш первый компонент {/*your-first-component*/} -Приложения React строятся из изолированных частей пользовательского интерфейса, называемых *компонентами*. Компонент React — это функция JavaScript, которую вы можете дополнить разметкой. Компоненты могут быть маленькими, как кнопка, или большими, как целая страница. Вот компонент `Gallery`, отображающий три компонента `Profile`: +Приложения React строятся из изолированных частей UI, называемых *компонентами*. Компонент React — это функция JavaScript, которую вы можете дополнить разметкой. Компоненты могут быть маленькими, как кнопка, или большими, как целая страница. Вот компонент `Gallery`, отображающий три компонента `Profile`: @@ -119,9 +118,9 @@ img { margin: 0 10px 10px 0; } ## Написание разметки с помощью JSX {/*writing-markup-with-jsx*/} -Каждый компонент React — это функция JavaScript, которая может содержать некоторую разметку, которую React отображает в браузере. Компоненты React используют расширение синтаксиса под названием JSX для представления этой разметки. JSX очень похож на HTML, но он немного строже и может отображать динамическую информацию. +Каждый компонент React — это функция JavaScript, которая может содержать разметку, которую React отображает в браузере. Компоненты React используют синтаксическое расширение под названием JSX для представления этой разметки. JSX очень похож на HTML, но он немного строже и может отображать динамическую информацию. -Если мы вставим существующую HTML-разметку в компонент React, это не всегда сработает: +Если мы вставим существующую HTML-разметку в компонент React, это не всегда будет работать: @@ -150,41 +149,412 @@ img { height: 90px; } -Если у вас есть существующий +Если у вас есть существующий HTML, подобный этому, вы можете исправить его с помощью [конвертера](https://transform.tools/html-to-jsx): + + + +```js +export default function TodoList() { + return ( + <> +

    Hedy Lamarr's Todos

    + Hedy Lamarr +
      +
    • Invent new traffic lights
    • +
    • Rehearse a movie scene
    • +
    • Improve spectrum technology
    • +
    + + ); +} +``` + +```css +img { height: 90px; } +``` + +
    + + + +Прочитайте **[Написание разметки с помощью JSX](/learn/writing-markup-with-jsx)**, чтобы узнать, как писать валидный JSX. + + + +## JavaScript в JSX с фигурными скобками {/*javascript-in-jsx-with-curly-braces*/} + +JSX позволяет писать разметку в стиле HTML внутри файла JavaScript, сохраняя логику рендеринга и контент в одном месте. Иногда вам захочется добавить немного логики JavaScript или сослаться на динамическое свойство внутри этой разметки. В такой ситуации вы можете использовать фигурные скобки в вашем JSX, чтобы "открыть окно" в JavaScript: + + + +```js +const person = { + name: 'Gregorio Y. Zara', + theme: { + backgroundColor: 'black', + color: 'pink' + } +}; + +export default function TodoList() { + return ( +
    +

    {person.name}'s Todos

    + Gregorio Y. Zara +
      +
    • Improve the videophone
    • +
    • Prepare aeronautics lectures
    • +
    • Work on the alcohol-fuelled engine
    • +
    +
    + ); +} +``` + +```css +body { padding: 0; margin: 0 } +body > div > div { padding: 20px; } +.avatar { border-radius: 50%; height: 90px; } +``` + +
    + + + +Прочитайте **[JavaScript в JSX с фигурными скобками](/learn/javascript-in-jsx-with-curly-braces)**, чтобы узнать, как получать доступ к данным JavaScript из JSX. + + + +## Передача пропсов компоненту {/*passing-props-to-a-component*/} + +Компоненты React используют *пропсы* для взаимодействия друг с другом. Каждый родительский компонент может передавать некоторую информацию своим дочерним компонентам, давая им пропсы. Пропсы могут напомнить вам HTML-атрибуты, но через них можно передавать любые значения JavaScript, включая объекты, массивы, функции и даже JSX! + + + +```js +import { getImageUrl } from './utils.js' + +export default function Profile() { + return ( + + + + ); +} + +function Avatar({ person, size }) { + return ( + {person.name} + ); +} + +function Card({ children }) { + return ( +
    + {children} +
    + ); +} + +``` + +```js src/utils.js +export function getImageUrl(person, size = 's') { + return ( + 'https://i.imgur.com/' + + person.imageId + + size + + '.jpg' + ); +} +``` + +```css +.card { + width: fit-content; + margin: 5px; + padding: 5px; + font-size: 20px; + text-align: center; + border: 1px solid #aaa; + border-radius: 20px; + background: #fff; +} +.avatar { + margin: 20px; + border-radius: 50%; +} +``` + +
    + + + +Прочитайте **[Передача пропсов компоненту](/learn/passing-props-to-a-component)**, чтобы узнать, как передавать и читать пропсы. + + + +## Условный рендеринг {/*conditional-rendering*/} + +Вашим компонентам часто придется отображать разные вещи в зависимости от разных условий. В React вы можете условно отображать JSX, используя синтаксис JavaScript, такой как `if` операторы, `&&` и операторы `? :`. + +В этом примере оператор `&&` JavaScript используется для условного отображения галочки: + + + +```js +function Item({ name, isPacked }) { + return ( +
  • + {name} {isPacked && '✅'} +
  • + ); +} + +export default function PackingList() { + return ( +
    +

    Sally Ride's Packing List

    +
      + + + +
    +
    + ); +} +``` + +
    + + + +Прочитайте **[Условный рендеринг](/learn/conditional-rendering)**, чтобы узнать о различных способах условного отображения контента. + + + +## Рендеринг списков {/*rendering-lists*/} + +Часто вам придется отображать несколько похожих компонентов из коллекции данных. Вы можете использовать `filter()` и `map()` в JavaScript с React, чтобы фильтровать и преобразовывать ваш массив данных в массив компонентов. + +Для каждого элемента массива вам нужно будет указать `key`. Обычно вы захотите использовать ID из базы данных в качестве `key`. Ключи позволяют React отслеживать местоположение каждого элемента в списке, даже если список изменяется. + + + +```js src/App.js +import { people } from './data.js'; +import { getImageUrl } from './utils.js'; + +export default function List() { + const listItems = people.map(person => +
  • + {person.name} +

    + {person.name}: + {' ' + person.profession + ' '} + known for {person.accomplishment} +

    +
  • + ); + return ( +
    +

    Scientists

    +
      {listItems}
    +
    + ); +} +``` + +```js src/data.js +export const people = [{ + id: 0, + name: 'Creola Katherine Johnson', + profession: 'mathematician', + accomplishment: 'spaceflight calculations', + imageId: 'MK3eW3A' +}, { + id: 1, + name: 'Mario José Molina-Pasquel Henríquez', + profession: 'chemist', + accomplishment: 'discovery of Arctic ozone hole', + imageId: 'mynHUSa' +}, { + id: 2, + name: 'Mohammad Abdus Salam', + profession: 'physicist', + accomplishment: 'electromagnetism theory', + imageId: 'bE7W1ji' +}, { + id: 3, + name: 'Percy Lavon Julian', + profession: 'chemist', + accomplishment: 'pioneering cortisone drugs, steroids and birth control pills', + imageId: 'IOjWm71' +}, { + id: 4, + name: 'Subrahmanyan Chandrasekhar', + profession: 'astrophysicist', + accomplishment: 'white dwarf star mass calculations', + imageId: 'lrWQx8l' +}]; +``` + +```js src/utils.js +export function getImageUrl(person) { + return ( + 'https://i.imgur.com/' + + person.imageId + + 's.jpg' + ); +} +``` + +```css +ul { list-style-type: none; padding: 0px 10px; } +li { + margin-bottom: 10px; + display: grid; + grid-template-columns: 1fr 1fr; + align-items: center; +} +img { width: 100px; height: 100px; border-radius: 50%; } +h1 { font-size: 22px; } +h2 { font-size: 20px; } +``` + +
    + + + +Прочитайте **[Рендеринг списков](/learn/rendering-lists)**, чтобы узнать, как отображать список компонентов и как выбирать ключ. + + + +## Сохранение чистоты компонентов {/*keeping-components-pure*/} + +Некоторые функции JavaScript являются *чистыми*. Чистая функция: + +* **Не вмешивается в чужие дела.** Она не изменяет объекты или переменные, которые существовали до её вызова. +* **Те же входные данные, тот же результат.** При одинаковых входных данных чистая функция всегда должна возвращать один и тот же результат. + +Строго следуя принципу написания компонентов как чистых функций, вы можете избежать целого класса запутанных ошибок и непредсказуемого поведения по мере роста вашей кодовой базы. Вот пример нечистого компонента: + + + +```js +let guest = 0; + +function Cup() { + // Плохо: изменение существующей переменной! + guest = guest + 1; + return

    Tea cup for guest #{guest}

    ; +} + +export default function TeaSet() { + return ( + <> + + + + + ); +} +``` + +
    + +Вы можете сделать этот компонент чистым, передав пропс вместо изменения существующей переменной: + + + +```js +function Cup({ guest }) { + return

    Tea cup for guest #{guest}

    ; +} + +export default function TeaSet() { + return ( + <> + + + + + ); +} +``` + +
    + + + +Прочитайте **[Сохранение чистоты компонентов](/learn/keeping-components-pure)**, чтобы узнать, как писать компоненты как чистые, предсказуемые функции. + + ## Ваш UI как дерево {/*your-ui-as-a-tree*/} React использует деревья для моделирования взаимосвязей между компонентами и модулями. -Дерево рендеринга React — это представление родительско-дочерних отношений между компонентами. +Дерево рендеринга React — это представление родительских и дочерних отношений между компонентами. - + Пример дерева рендеринга React. -Компоненты, расположенные ближе к вершине дерева, рядом с корневым компонентом, считаются компонентами верхнего уровня. Компоненты без дочерних компонентов являются листовыми компонентами. Такая категоризация компонентов полезна для понимания потока данных и производительности рендеринга. +Компоненты, находящиеся ближе к вершине дерева, рядом с корневым компонентом, считаются компонентами верхнего уровня. Компоненты без дочерних компонентов являются листовыми компонентами. Эта категоризация компонентов полезна для понимания потока данных и производительности рендеринга. -Моделирование взаимосвязей между JavaScript-модулями — ещё один полезный способ понять ваше приложение. Мы называем это деревом зависимостей модулей. +Моделирование взаимосвязей между модулями JavaScript — еще один полезный способ понять ваше приложение. Мы называем это деревом зависимостей модулей. - + Пример дерева зависимостей модулей. -Дерево зависимостей часто используется инструментами сборки для объединения всего необходимого JavaScript-кода, который клиент должен скачать и отрисовать. Большой размер бандла ухудшает пользовательский опыт в React-приложениях. Понимание дерева зависимостей модулей помогает отлаживать такие проблемы. +Дерево зависимостей часто используется инструментами сборки для объединения всего релевантного кода JavaScript, который клиент должен загрузить и отобразить. Большой размер бандла ухудшает пользовательский опыт в приложениях React. Понимание дерева зависимостей модулей полезно для отладки таких проблем. -Прочтите **[Ваш UI как дерево](/learn/understanding-your-ui-as-a-tree)**, чтобы узнать, как создавать деревья рендеринга и зависимостей модулей для React-приложения и как они являются полезными ментальными моделями для улучшения пользовательского опыта и производительности. +Прочитайте **[Ваш UI как дерево](/learn/understanding-your-ui-as-a-tree)**, чтобы узнать, как создавать деревья рендеринга и деревья зависимостей модулей для приложения React, и как они являются полезными ментальными моделями для улучшения пользовательского опыта и производительности. - ## Что дальше? {/*whats-next*/} -Перейдите к [Ваш первый компонент](/learn/your-first-component), чтобы начать читать эту главу по страницам! +Перейдите к [Ваш первый компонент](/learn/your-first-component), чтобы начать читать эту главу страница за страницей! Или, если вы уже знакомы с этими темами, почему бы не прочитать о [Добавлении интерактивности](/learn/adding-interactivity)? \ No newline at end of file