diff --git a/src/content/learn/sharing-state-between-components.md b/src/content/learn/sharing-state-between-components.md index 149164fe19..b3ee2c8854 100644 --- a/src/content/learn/sharing-state-between-components.md +++ b/src/content/learn/sharing-state-between-components.md @@ -1,31 +1,29 @@ --- -title: Sharing State Between Components +title: Совместное использование состояния между компонентами --- -Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as *lifting state up,* and it's one of the most common things you will do writing React code. +Иногда требуется, чтобы состояние двух компонентов всегда изменялось вместе. Для этого нужно удалить состояние из обоих компонентов, переместить его в ближайшего общего родителя и передать его им через пропсы. Это называется *подъемом состояния вверх* и является одним из наиболее распространенных приемов при написании кода на React. - -- How to share state between components by lifting it up -- What are controlled and uncontrolled components +- Как использовать одно состояние между компонентами, подняв его вверх +- Что такое управляемые и неуправляемые компоненты -## Lifting state up by example {/*lifting-state-up-by-example*/} - -In this example, a parent `Accordion` component renders two separate `Panel`s: +## Подъём состояния на примере {/*lifting-state-up-by-example*/} +В этом примере родительский компонент `Accordion` рендерит два отдельных компонента `Panel`: * `Accordion` - `Panel` - `Panel` -Each `Panel` component has a boolean `isActive` state that determines whether its content is visible. +Каждый компонент `Panel` имеет булевое состояние `isActive`, которое определяет, будет ли его содержимое видимым. -Press the Show button for both panels: +Нажмите кнопку Показать на обеих панелях: @@ -41,7 +39,7 @@ function Panel({ title, children }) {

{children}

) : ( )} @@ -51,12 +49,12 @@ function Panel({ title, children }) { export default function Accordion() { return ( <> -

Almaty, Kazakhstan

- - With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city. +

Алматы, Казахстан

+ + Алматы с населением около 2 миллионов человек является крупнейшим городом Казахстана. С 1929 по 1997 год этот город был столицей. - - The name comes from алма, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild Malus sieversii is considered a likely candidate for the ancestor of the modern domestic apple. + + Название происходит от алма, казахского слова, означающего «яблоко», и часто переводится как «полное яблок». На самом деле, регион, прилегающий к Алматы, считается прародиной яблони, а дикий Malus sieversii считается вероятным кандидатом на роль предка современного домашнего яблока. ); @@ -73,59 +71,59 @@ h3, p { margin: 5px 0px; }
-Notice how pressing one panel's button does not affect the other panel--they are independent. +Обратите внимание, что нажатие кнопки на одной панели не влияет на другую панель--они независимы. - + -Initially, each `Panel`'s `isActive` state is `false`, so they both appear collapsed +Изначально, каждая панель имеет состояние `isActive` в значении `false`, поэтому они обе отображаются свернутыми - + -Clicking either `Panel`'s button will only update that `Panel`'s `isActive` state alone +Нажатие кнопки на одной из панелей приведет к обновлению состояния `isActive` только этой панели -**But now let's say you want to change it so that only one panel is expanded at any given time.** With that design, expanding the second panel should collapse the first one. How would you do that? +**А теперь предположим, что вы хотите изменить поведение так, чтобы в любой момент времени была раскрыта только одна панель.** В таком случае раскрытие второй панели должно привести к сворачиванию первой. Как бы вы это сделали? -To coordinate these two panels, you need to "lift their state up" to a parent component in three steps: +Чтобы согласовать поведение этих двух панелей, вам нужно «поднять их состояние» в родительский компонент в три шага: -1. **Remove** state from the child components. -2. **Pass** hardcoded data from the common parent. -3. **Add** state to the common parent and pass it down together with the event handlers. +1. **Удалите** состояние из дочерних компонентов. +2. **Передайте** данные хардкодом из общего родителя. +3. **Добавьте** состояние в общего родителя и передайте его вместе с обработчиками событий. -This will allow the `Accordion` component to coordinate both `Panel`s and only expand one at a time. +Это позволит компоненту `Accordion` управлять обеими панелями и раскрывать только по одной за раз. -### Step 1: Remove state from the child components {/*step-1-remove-state-from-the-child-components*/} +### Шаг 1: Удалить состояние из дочерних компонентов {/*step-1-remove-state-from-the-child-components*/} -You will give control of the `Panel`'s `isActive` to its parent component. This means that the parent component will pass `isActive` to `Panel` as a prop instead. Start by **removing this line** from the `Panel` component: +Вы передадите управление значением `isActive` родительскому компоненту `Panel`. Это означает, что родительский компонент будет передавать значение `isActive` через проп, вместо того, чтобы хранить это состояние в `Panel`. Начните с **удаления этой строки** из компонента `Panel`: ```js const [isActive, setIsActive] = useState(false); ``` -And instead, add `isActive` to the `Panel`'s list of props: +И вместо нее, добавьте `isActive` в список пропсов `Panel`: ```js function Panel({ title, children, isActive }) { ``` -Now the `Panel`'s parent component can *control* `isActive` by [passing it down as a prop.](/learn/passing-props-to-a-component) Conversely, the `Panel` component now has *no control* over the value of `isActive`--it's now up to the parent component! +Теперь родитель компонента `Panel` может *управлять* `isActive`, [передавая его вниз как проп.](/learn/passing-props-to-a-component) С другой стороны, компонент `Panel` теперь *не имеет контроля* над значением `isActive`--теперь оно зависит от родительского компонента! -### Step 2: Pass hardcoded data from the common parent {/*step-2-pass-hardcoded-data-from-the-common-parent*/} +### Шаг 2: Передать данные хардкодом из общего родителя {/*step-2-pass-hardcoded-data-from-the-common-parent*/} -To lift state up, you must locate the closest common parent component of *both* of the child components that you want to coordinate: +Чтобы поднять состояние, вам необходимо определить ближайшего общего родителя для обоих дочерних компонентов, которые вы хотите скоординировать: -* `Accordion` *(closest common parent)* +* `Accordion` *(ближайший общий родитель)* - `Panel` - `Panel` -In this example, it's the `Accordion` component. Since it's above both panels and can control their props, it will become the "source of truth" for which panel is currently active. Make the `Accordion` component pass a hardcoded value of `isActive` (for example, `true`) to both panels: +В данном примере это компонент `Accordion`. Поскольку он находится выше обеих панелей и может контролировать их пропсы, он станет «источником истины», чтобы определить, какая панель сейчас активна. Давайте сделаем так, чтобы `Accordion` передавал значения `isActive` хардкодом (например, `true`) обеим панелям: @@ -135,12 +133,12 @@ import { useState } from 'react'; export default function Accordion() { return ( <> -

Almaty, Kazakhstan

- - With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city. +

Алматы, Казахстан

+ + Алматы с населением около 2 миллионов человек является крупнейшим городом Казахстана. С 1929 по 1997 год этот город был столицей. - - The name comes from алма, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild Malus sieversii is considered a likely candidate for the ancestor of the modern domestic apple. + + Название происходит от алма, казахского слова, означающего «яблоко», и часто переводится как «полное яблок». На самом деле, регион, прилегающий к Алматы, считается прародиной яблони, а дикий Malus sieversii считается вероятным кандидатом на роль предка современного домашнего яблока. ); @@ -154,7 +152,7 @@ function Panel({ title, children, isActive }) {

{children}

) : ( )} @@ -172,21 +170,21 @@ h3, p { margin: 5px 0px; }
-Try editing the hardcoded `isActive` values in the `Accordion` component and see the result on the screen. +Попробуйте изменить хардкод значение `isActive` в компоненте `Accordion` и обратите внимание как это повлияет на результат. -### Step 3: Add state to the common parent {/*step-3-add-state-to-the-common-parent*/} +### Шаг 3: Добавить состояние в общего родителя {/*step-3-add-state-to-the-common-parent*/} -Lifting state up often changes the nature of what you're storing as state. +Подъём состояния часто приводит к изменению сущности хранимого состояния. -In this case, only one panel should be active at a time. This means that the `Accordion` common parent component needs to keep track of *which* panel is the active one. Instead of a `boolean` value, it could use a number as the index of the active `Panel` for the state variable: +В нашем случае, только одна панель должна быть активна одновременно. Это означает, что общему родителю `Accordion` нужно следить за тем *какая* панель активна в данный момент. Вместо булевого значения в состоянии можно хранить число, которое будет означать индекс активной панели: ```js const [activeIndex, setActiveIndex] = useState(0); ``` -When the `activeIndex` is `0`, the first panel is active, and when it's `1`, it's the second one. +Когда `activeIndex` равен `0`, активна первая панель, а когда равен `1`, активна вторая. -Clicking the "Show" button in either `Panel` needs to change the active index in `Accordion`. A `Panel` can't set the `activeIndex` state directly because it's defined inside the `Accordion`. The `Accordion` component needs to *explicitly allow* the `Panel` component to change its state by [passing an event handler down as a prop](/learn/responding-to-events#passing-event-handlers-as-props): +Нажатие на кнопку «Показать» в любой из панелей должно изменять индекс активной панели в `Accordion`. `Panel` не может напрямую установить состояние `activeIndex`, потому что оно определено внутри `Accordion`. Компоненту `Accordion` необходимо *явно разрешить* компоненту `Panel` изменять свое состояние, [передав обработчик события как проп](/learn/responding-to-events#passing-event-handlers-as-props): ```js <> @@ -205,7 +203,7 @@ Clicking the "Show" button in either `Panel` needs to change the active index in ``` -The ` )} @@ -266,19 +264,19 @@ h3, p { margin: 5px 0px; } -This completes lifting state up! Moving state into the common parent component allowed you to coordinate the two panels. Using the active index instead of two "is shown" flags ensured that only one panel is active at a given time. And passing down the event handler to the child allowed the child to change the parent's state. +Подъём состояния завершен! Переместив состояние в общий родительский компонент нам удалось скоординировать две панели. Использование индекса активной панели вместо двух флагов `isActive` гарантирует нам, что будет активна только одна панель одновременно. А передав обработчики событий дочерним компонентам мы позволили им управлять состоянием родителя. - + -Initially, `Accordion`'s `activeIndex` is `0`, so the first `Panel` receives `isActive = true` +В начале, `activeIndex` в компоненте `Accordion` имеет значение 0, поэтому первая панель получает `isActive = true` - + -When `Accordion`'s `activeIndex` state changes to `1`, the second `Panel` receives `isActive = true` instead +Когда состояние `activeIndex` в `Accordion` становится `1`, вторая `Panel` получает `isActive = true` вместо первой @@ -286,48 +284,48 @@ When `Accordion`'s `activeIndex` state changes to `1`, the second `Panel` receiv -#### Controlled and uncontrolled components {/*controlled-and-uncontrolled-components*/} +#### Управляемые и неуправляемые компоненты {/*controlled-and-uncontrolled-components*/} -It is common to call a component with some local state "uncontrolled". For example, the original `Panel` component with an `isActive` state variable is uncontrolled because its parent cannot influence whether the panel is active or not. +Компоненты, у которых есть внутреннее состояние, обычно называют «неуправляемыми». Например, оригинальный компонент `Panel` с переменной состояния `isActive` является неуправляемым, потому что его родитель не может повлиять на то, активна ли панель. -In contrast, you might say a component is "controlled" when the important information in it is driven by props rather than its own local state. This lets the parent component fully specify its behavior. The final `Panel` component with the `isActive` prop is controlled by the `Accordion` component. +Напротив, компонент называют «управляемым», если важная информация зависит от пропов, а не от внутреннего состояния. Это позволяет родительскому компоненту полностью контролировать его поведение. После наших изменений, компонентом `Panel` управляет компонент `Accordion` с помощью пропа `isActive`. -Uncontrolled components are easier to use within their parents because they require less configuration. But they're less flexible when you want to coordinate them together. Controlled components are maximally flexible, but they require the parent components to fully configure them with props. +Неуправляемые компоненты проще использовать, потому что им необходимо меньше конфигурации. Но они не такие гибкие, когда вам нужно согласовать их поведение. Управляемые компоненты максимально гибкие, но необходимо чтобы родительские компоненты полностью настраивали их через пропсы. -In practice, "controlled" and "uncontrolled" aren't strict technical terms--each component usually has some mix of both local state and props. However, this is a useful way to talk about how components are designed and what capabilities they offer. +На практике «управляемые» и «неуправляемые» это не строгие технические определения--обычно компоненты имеют и внутреннее состояние и пропсы. Однако, важно понимать как устроены компоненты и какие возможности они предоставляют. -When writing a component, consider which information in it should be controlled (via props), and which information should be uncontrolled (via state). But you can always change your mind and refactor later. +Когда пишите компонент, подумайте какая информация в нем должна быть управляема (через пропсы), а какая неуправляема (через состояние). Но вы в любой момент можете передумать и сделать рефакторинг позже. -## A single source of truth for each state {/*a-single-source-of-truth-for-each-state*/} +## Единый источник истины для каждого состояния {/*a-single-source-of-truth-for-each-state*/} -In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React state, and passing it down by props! +В приложении на React у многих компонентов будет свое собственное состояние. Какое-то состояние может «жить» близко к листовым компонентам (компоненты внизу дерева), например, текстовое поле. Другое состояние может «жить» ближе к корню приложения. Например, даже при реализации библиотеки клиентской маршрутизации, текущий путь обычно сохраняют в состояние React и передают его вниз через пропсы. -**For each unique piece of state, you will choose the component that "owns" it.** This principle is also known as having a ["single source of truth".](https://en.wikipedia.org/wiki/Single_source_of_truth) It doesn't mean that all state lives in one place--but that for _each_ piece of state, there is a _specific_ component that holds that piece of information. Instead of duplicating shared state between components, *lift it up* to their common shared parent, and *pass it down* to the children that need it. +**Для каждого уникального кусочка состояния вы выбираете компонент, который «владеет» им.** Этот принцип также известен как наличие ["единого источника истины".](https://en.wikipedia.org/wiki/Single_source_of_truth) Это не означает, что все состояние React находится в одном месте--для _каждой_ части состояния существует _конкретный_ компонент, который хранит эту информацию. Вместо дублирования общего состояния между компонентами, *поднимите* его в общий родительский компонент и «пробросьте» его дочерним компонентам, которым он необходим. -Your app will change as you work on it. It is common that you will move state down or back up while you're still figuring out where each piece of the state "lives". This is all part of the process! +Ваше приложение будет меняться по мере работы над ним. Это нормально, что вы будете перемещать состояние вниз или обратно вверх, пока разбираетесь где «живет» каждая часть состояния. Это все часть процесса! -To see what this feels like in practice with a few more components, read [Thinking in React.](/learn/thinking-in-react) +Чтобы увидеть как это работает на практике с другими компонентами, прочитайте статью [Мыслим на React.](/learn/thinking-in-react). -* When you want to coordinate two components, move their state to their common parent. -* Then pass the information down through props from their common parent. -* Finally, pass the event handlers down so that the children can change the parent's state. -* It's useful to consider components as "controlled" (driven by props) or "uncontrolled" (driven by state). +* Если вы хотите скоординировать два компонента, переместите их состояние к общему родительскому компоненту. +* Затем передайте информацию через пропсы из общего родительского компонента. +* Наконец, пробросьте обработчики событий, чтобы дочерние компоненты могли изменять состояние родительского компонента. +* Полезно рассматривать компоненты как «управляемые» (управляемые пропами) или «неуправляемые» (управляемые состоянием). -#### Synced inputs {/*synced-inputs*/} +#### Синхронизированные поля ввода {/*synced-inputs*/} -These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa. +Эти два поля ввода независимы. Синхронизируйте их: редактирование одного поля должно обновлять другое поле с тем же текстом, и наоборот. -You'll need to lift their state up into the parent component. +Вам нужно поднять их состояние в родительский компонент. @@ -339,8 +337,8 @@ import { useState } from 'react'; export default function SyncedInputs() { return ( <> - - + + ); } @@ -374,7 +372,7 @@ label { display: block; } -Move the `text` state variable into the parent component along with the `handleChange` handler. Then pass them down as props to both of the `Input` components. This will keep them in sync. +Переместите переменную состояния `text` в родительский компонент вместе с обработчиком `handleChange`. Затем передайте их вниз как пропсы обоим компонентам `Input`. Таким образом они будут синхронизированы. @@ -391,12 +389,12 @@ export default function SyncedInputs() { return ( <> @@ -427,17 +425,17 @@ label { display: block; } -#### Filtering a list {/*filtering-a-list*/} +#### Фильтрация списка {/*filtering-a-list*/} -In this example, the `SearchBar` has its own `query` state that controls the text input. Its parent `FilterableList` component displays a `List` of items, but it doesn't take the search query into account. +В этом примере у компонента `SearchBar` есть своё состояние query, которое управляет текстовым полем. Родительский компонент `FilterableList` отображает список элементов `List`, но не учитывает поисковый запрос. -Use the `filterItems(foods, query)` function to filter the list according to the search query. To test your changes, verify that typing "s" into the input filters down the list to "Sushi", "Shish kebab", and "Dim sum". +Используйте функцию `filterItems(foods, query)`, чтобы отфильтровать список в соответствии с поисковым запросом. Чтобы проверить свои изменения, убедитесь, что ввод буквы «s» в поле ввода отфильтрует список так, что остануться элементы «Sushi», «Shish kebab» и «Dim sum». -Note that `filterItems` is already implemented and imported so you don't need to write it yourself! +Обратите внимание, что функция `filterItems` уже реализована и импортирована, поэтому вам не нужно писать её самостоятельно! -You will want to remove the `query` state and the `handleChange` handler from the `SearchBar`, and move them to the `FilterableList`. Then pass them down to `SearchBar` as `query` and `onChange` props. +Вам нужно удалить состояние `query` и обработчик `handleChange` из компонента `SearchBar` и переместить их в `FilterableList`. Затем передать их вниз в `SearchBar` как пропсы `query` и `onChange`. @@ -466,7 +464,7 @@ function SearchBar() { return (