From d510a1b0e6d35c491369bf8040f3e4e5d79d8219 Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Thu, 4 Jun 2026 14:19:09 +0000 Subject: [PATCH] =?UTF-8?q?docs:=20translate=20`sharing-state-between-comp?= =?UTF-8?q?onents.md`=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 --- .../learn/sharing-state-between-components.md | 130 +++++++++--------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/src/content/learn/sharing-state-between-components.md b/src/content/learn/sharing-state-between-components.md index 52eaf28f85..a3fd086bde 100644 --- a/src/content/learn/sharing-state-between-components.md +++ b/src/content/learn/sharing-state-between-components.md @@ -4,28 +4,28 @@ title: Sharing State Between Components -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. +Иногда вам нужно, чтобы состояние двух компонентов изменялось одновременно. Для этого удалите состояние из обоих компонентов, переместите его в их ближайший общий родительский компонент и затем передайте его им через пропсы. Это называется *подъём состояния вверх* (lifting state up) и является одной из самых частых операций при написании кода на 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*/} +## Подъём состояния вверх на примере {/*lifting-state-up-by-example*/} -In this example, a parent `Accordion` component renders two separate `Panel`s: +В этом примере родительский компонент `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: +Нажмите кнопку "Show" для обеих панелей: @@ -73,59 +73,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` каждого `Panel` равно `false`, поэтому обе панели отображаются свёрнутыми. - + -Clicking either `Panel`'s button will only update that `Panel`'s `isActive` state alone +При нажатии на кнопку любой `Panel` обновляется только состояние `isActive` этой `Panel`. -**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` координировать оба `Panel` и разворачивать только одну панель за раз. -### 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`) обеим панелям: @@ -172,21 +172,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` должен отслеживать, *какая* панель является активной. Вместо булева значения он может использовать число в качестве индекса активной `Panel` для переменной состояния: ```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): +Нажатие кнопки "Show" в любой `Panel` должно изменять активный индекс в `Accordion`. `Panel` не может напрямую установить состояние `activeIndex`, потому что оно определено внутри `Accordion`. Компонент `Accordion` должен *явно разрешить* компоненту `Panel` изменять своё состояние, [передав обработчик событий в качестве пропса.](/learn/responding-to-events#passing-event-handlers-as-props) ```js <> @@ -205,7 +205,7 @@ Clicking the "Show" button in either `Panel` needs to change the active index in ``` -The `