From bff009959caf89302686856dcbac720adf46856f Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Thu, 14 May 2026 15:34:33 +0000 Subject: [PATCH 1/3] =?UTF-8?q?docs:=20translate=20`ViewTransition.md`=20t?= =?UTF-8?q?o=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/reference/react/ViewTransition.md | 1419 +---------------- 1 file changed, 82 insertions(+), 1337 deletions(-) diff --git a/src/content/reference/react/ViewTransition.md b/src/content/reference/react/ViewTransition.md index b0dc7b571b..c5111bb6a2 100644 --- a/src/content/reference/react/ViewTransition.md +++ b/src/content/reference/react/ViewTransition.md @@ -1,26 +1,25 @@ --- -title: +title: "``" version: experimental --- - +```html -**This API is experimental and is not available in a stable version of React yet.** +**Этот API является экспериментальным и пока недоступен в стабильной версии React.** -You can try it by upgrading React packages to the most recent experimental version: +Вы можете попробовать его, обновив пакеты React до самой последней экспериментальной версии: - `react@experimental` - `react-dom@experimental` - `eslint-plugin-react-hooks@experimental` -Experimental versions of React may contain bugs. Don't use them in production. +Экспериментальные версии React могут содержать ошибки. Не используйте их в продакшене. -`` lets you animate elements that update inside a Transition. - +`` позволяет анимировать элементы, которые обновляются внутри Transition. ```js import {unstable_ViewTransition as ViewTransition} from 'react'; @@ -36,97 +35,96 @@ import {unstable_ViewTransition as ViewTransition} from 'react'; --- -## Reference {/*reference*/} +## Ссылка {/*reference*/} ### `` {/*viewtransition*/} -Wrap elements in `` to animate them when they update inside a [Transition](/reference/react/useTransition). React uses the following heuristics to determine if a View Transition activates for an animation: +Оберните элементы в ``, чтобы анимировать их при обновлении внутри [Transition](/reference/react/useTransition). React использует следующие эвристики, чтобы определить, активируется ли View Transition для анимации: -- `enter`: If a `ViewTransition` itself gets inserted in this Transition, then this will activate. -- `exit`: If a `ViewTransition` itself gets deleted in this Transition, then this will activate. -- `update`: If a `ViewTransition` has any DOM mutations inside it that React is doing (such as a prop changing) or if the `ViewTransition` boundary itself changes size or position due to an immediate sibling. If there are nested` ViewTransition` then the mutation applies to them and not the parent. -- `share`: If a named `ViewTransition` is inside a deleted subtree and another named `ViewTransition` with the same name is part of an inserted subtree in the same Transition, they form a Shared Element Transition, and it animates from the deleted one to the inserted one. +- `enter`: Если сам `ViewTransition` вставляется в этот Transition, то он активируется. +- `exit`: Если сам `ViewTransition` удаляется в этом Transition, то он активируется. +- `update`: Если в `ViewTransition` есть какие-либо изменения DOM, которые выполняет React (например, изменение пропса), или если сама граница `ViewTransition` изменяет размер или положение из-за непосредственного соседа. Если есть вложенные `ViewTransition`, то изменение применяется к ним, а не к родителю. +- `share`: Если именованный `ViewTransition` находится внутри удаленного поддерева, а другой именованный `ViewTransition` с тем же именем является частью вставленного поддерева в том же Transition, они образуют Shared Element Transition, и он анимируется от удаленного к вставленному. -By default, `` animates with a smooth cross-fade (the browser default view transition). You can customize the animation by providing a [View Transition Class](#view-transition-class) to the `` component. You can customize animations for each kind of trigger (see [Styling View Transitions](#styling-view-transitions)). +По умолчанию `` анимирует с плавным переходом (переход представления по умолчанию в браузере). Вы можете настроить анимацию, предоставив [класс View Transition](#view-transition-class) компоненту ``. Вы можете настроить анимацию для каждого типа триггера (см. [Стилизация View Transitions](#styling-view-transitions)). -#### How does `` work? {/*how-does-viewtransition-work*/} +#### Как работает ``? {/*how-does-viewtransition-work*/} -Under the hood, React applies `view-transition-name` to inline styles of the nearest DOM node nested inside the `` component. If there are multiple sibling DOM nodes like `
` then React adds a suffix to the name to make each unique but conceptually they're part of the same one. React doesn't apply these eagerly but only at the time that boundary should participate in an animation. +В основе React применяет `view-transition-name` к встроенным стилям ближайшего узла DOM, вложенного в компонент ``. Если есть несколько соседних узлов DOM, таких как `
`, то React добавляет суффикс к имени, чтобы сделать каждый уникальным, но концептуально они являются частью одного и того же. React не применяет их немедленно, а только в то время, когда граница должна участвовать в анимации. -React automatically calls `startViewTransition` itself behind the scenes so you should never do that yourself. In fact, if you have something else on the page running a ViewTransition React will interrupt it. So it's recommended that you use React itself to coordinate these. If you had other ways of trigger ViewTransitions in the past, we recommend that you migrate to the built-in way. +React автоматически вызывает `startViewTransition` сам по себе за кулисами, поэтому вам никогда не следует делать это самостоятельно. Фактически, если у вас есть что-то еще на странице, запускающее ViewTransition, React прервет его. Поэтому рекомендуется использовать сам React для координации этих действий. Если у вас были другие способы запуска ViewTransitions в прошлом, мы рекомендуем вам перейти на встроенный способ. -If there are other React ViewTransitions already running then React will wait for them to finish before starting the next one. However, importantly if there are multiple updates happening while the first one is running, those will all be batched into one. If you start A->B. Then in the meantime you get an update to go to C and then D. When the first A->B animation finishes the next one will animate from B->D. +Если уже запущены другие React ViewTransitions, то React будет ждать их завершения, прежде чем запускать следующий. Однако, что важно, если происходит несколько обновлений, пока выполняется первое, они все будут объединены в одно. Если вы запустите A->B. Затем, тем временем, вы получите обновление, чтобы перейти к C, а затем к D. Когда первая анимация A->B завершится, следующая будет анимироваться от B->D. -The `getSnapshotBeforeUpdate` life-cycle will be called before `startViewTransition` and some `view-transition-name` will update at the same time. +Жизненный цикл `getSnapshotBeforeUpdate` будет вызван перед `startViewTransition`, и некоторое `view-transition-name` обновится одновременно. -Then React calls `startViewTransition`. Inside the `updateCallback`, React will: +Затем React вызывает `startViewTransition`. Внутри `updateCallback` React будет: -- Apply its mutations to the DOM and invoke useInsertionEffects. -- Wait for fonts to load. -- Call componentDidMount, componentDidUpdate, useLayoutEffect and refs. -- Wait for any pending Navigation to finish. -- Then React will measure any changes to the layout to see which boundaries will need to animate. +- Применять свои изменения к DOM и вызывать useInsertionEffects. +- Ждать загрузки шрифтов. +- Вызывать componentDidMount, componentDidUpdate, useLayoutEffect и refs. +- Ждать завершения любой ожидающей навигации. +- Затем React измерит любые изменения в макете, чтобы увидеть, какие границы нужно будет анимировать. -After the ready Promise of the `startViewTransition` is resolved, React will then revert the `view-transition-name`. Then React will invoke the `onEnter`, `onExit`, `onUpdate` and `onShare` callbacks to allow for manual programmatic control over the Animations. This will be after the built-in default ones have already been computed. +После того, как Promise `startViewTransition` будет разрешен, React затем вернет `view-transition-name`. Затем React вызовет обратные вызовы `onEnter`, `onExit`, `onUpdate` и `onShare`, чтобы обеспечить ручное программное управление анимациями. Это произойдет после того, как встроенные значения по умолчанию уже будут вычислены. -If a `flushSync` happens to get in the middle of this sequence, then React will skip the Transition since it relies on being able to complete synchronously. +Если `flushSync` попадет в середину этой последовательности, то React пропустит Transition, поскольку он полагается на возможность завершения синхронно. -After the finished Promise of the `startViewTransition` is resolved, React will then invoke `useEffect`. This prevents those from interfering with the performance of the Animation. However, this is not a guarantee because if another `setState` happens while the Animation is running it'll still have to invoke the `useEffect` earlier to preserve the sequential guarantees. +После того, как Promise `startViewTransition` будет разрешен, React затем вызовет `useEffect`. Это предотвращает их вмешательство в производительность Animation. Однако это не гарантия, потому что, если произойдет еще один `setState`, пока Animation выполняется, ему все равно придется вызвать `useEffect` раньше, чтобы сохранить последовательные гарантии. -#### Props {/*props*/} +#### Пропсы {/*props*/} -By default, `` animates with a smooth cross-fade. You can customize the animation, or specify a shared element transition, with these props: +По умолчанию `` анимирует с плавным переходом. Вы можете настроить анимацию или указать переход общего элемента с помощью этих пропсов: -* **optional** `enter`: A string or object. The [View Transition Class](#view-transition-class) to apply when enter is activated. -* **optional** `exit`: A string or object. The [View Transition Class](#view-transition-class) to apply when exit is activated. -* **optional** `update`: A string or object. The [View Transition Class](#view-transition-class) to apply when an update is activated. -* **optional** `share`: A string or object. The [View Transition Class](#view-transition-class) to apply when a shared element is activated. -* **optional** `default`: A string or object. The [View Transition Class](#view-transition-class) used when no other matching activation prop is found. -* **optional** `name`: A string or object. The name of the View Transition used for shared element transitions. If not provided, React will use a unique name for each View Transition to prevent unexpected animations. +* **необязательный** `enter`: строка или объект. [Класс View Transition](#view-transition-class) для применения при активации enter. +* **необязательный** `exit`: строка или объект. [Класс View Transition](#view-transition-class) для применения при активации exit. +* **необязательный** `update`: строка или объект. [Класс View Transition](#view-transition-class) для применения при активации обновления. +* **необязательный** `share`: строка или объект. [Класс View Transition](#view-transition-class) для применения при активации общего элемента. +* **необязательный** `default`: строка или объект. [Класс View Transition](#view-transition-class), используемый, когда не найден ни один другой соответствующий проп активации. +* **необязательный** `name`: строка или объект. Имя View Transition, используемое для переходов общих элементов. Если не указано, React будет использовать уникальное имя для каждого View Transition, чтобы предотвратить непредвиденные анимации. #### Callback {/*events*/} -These callbacks allow you to adjust the animation imperatively using the [animate](https://developer.mozilla.org/en-US/docs/Web/API/Element/animate) APIs: +Эти обратные вызовы позволяют вам настраивать анимацию императивно с помощью [animate](https://developer.mozilla.org/en-US/docs/Web/API/Element/animate) API: -* **optional** `onEnter`: A function. React calls `onEnter` after an "enter" animation. -* **optional** `onExit`: A function. React calls `onExit` after an "exit" animation. -* **optional** `onShare`: A function. React calls `onShare` after a "share" animation. -* **optional** `onUpdate`: A function. React calls `onUpdate` after an "update" animation. +* **необязательный** `onEnter`: функция. React вызывает `onEnter` после анимации "enter". +* **необязательный** `onExit`: функция. React вызывает `onExit` после анимации "exit". +* **необязательный** `onShare`: функция. React вызывает `onShare` после анимации "share". +* **необязательный** `onUpdate`: функция. React вызывает `onUpdate` после анимации "update". -Each callback receives as arguments: -- `element`: The DOM element that was animated. -- `types`: The [Transition Types](/reference/react/addTransitionType) included in the animation. +Каждый обратный вызов получает в качестве аргументов: +- `element`: элемент DOM, который был анимирован. +- `types`: [Типы переходов](/reference/react/addTransitionType), включенные в анимацию. -### View Transition Class {/*view-transition-class*/} +### Класс View Transition {/*view-transition-class*/} -The View Transition Class is the CSS class name(s) applied by React during the transition when the ViewTransition activates. It can be a string or an object. -- `string`: the `class` added on the child elements when activated. If `'none'` is provided, no class will be added. -- `object`: the class added on the child elements will be the key matching View Transition type added with `addTransitionType`. The object can also specify a `default` to use if no matching type is found. +Класс View Transition — это имя(названия) CSS-класса, применяемое React во время перехода при активации ViewTransition. Это может быть строка или объект. +- `string`: `class`, добавленный к дочерним элементам при активации. Если предоставлено `'none'`, класс не будет добавлен. +- `object`: класс, добавленный к дочерним элементам, будет ключом, соответствующим типу View Transition, добавленным с помощью `addTransitionType`. Объект также может указывать `default` для использования, если не найден соответствующий тип. -The value `'none'` can be used to prevent a View Transition from activating for a specific trigger. +Значение `'none'` можно использовать, чтобы предотвратить активацию View Transition для определенного триггера. -### Styling View Transitions {/*styling-view-transitions*/} +### Стилизация View Transitions {/*styling-view-transitions*/} -In many early examples of View Transitions around the web, you'll have seen using a [`view-transition-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/view-transition-name) and then style it using `::view-transition-...(my-name)` selectors. We don't recommend that for styling. Instead, we normally recommend using a View Transition Class instead. +Во многих ранних примерах View Transitions в сети вы увидите использование [`view-transition-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/view-transition-name), а затем стилизацию с помощью селекторов `::view-transition-...(my-name)`. Мы не рекомендуем это для стилизации. Вместо этого мы обычно рекомендуем использовать класс View Transition. -To customize the animation for a `` you can provide a View Transition Class to one of the activation props. The View Transition Class is a CSS class name that React applies to the child elements when the ViewTransition activates. - -For example, to customize an "enter" animation, provide a class name to the `enter` prop: +Чтобы настроить анимацию для ``, вы можете предоставить класс View Transition одному из пропсов активации. Класс View Transition — это имя CSS-класса, которое React применяет к дочерним элементам при активации ViewTransition. +Например, чтобы настроить анимацию "enter", предоставьте имя класса пропсу `enter`: ```js ``` -When the `` activates an "enter" animation, React will add the class name `slide-in`. Then you can refer to this class using [view transition pseudo selectors](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API#pseudo-elements) to build reusable animations: +Когда `` активирует анимацию "enter", React добавит имя класса `slide-in`. Затем вы можете ссылаться на этот класс, используя [псевдоселекторы перехода представления](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API#pseudo-elements), чтобы создавать многоразовые анимации: ```css ::view-transition-group(.slide-in) { @@ -139,23 +137,22 @@ When the `` activates an "enter" animation, React will add the c } ``` -In the future, CSS libraries may add built-in animations using View Transition Classes to make this easier to use. +В будущем библиотеки CSS могут добавить встроенные анимации, используя классы View Transition, чтобы упростить использование. -#### Caveats {/*caveats*/} +#### Предостережения {/*caveats*/} -- By default, `setState` updates immediately and does not activate ``, only updates wrapped in a [Transition](/reference/react/useTransition). You can also use [``](/reference/react/Suspense) to opt-in to a Transition to [reveal content](/link-to-suspense-below). -- `` creates an image that can be moved around, scaled and cross-faded. Unlike Layout Animations you may have seen in React Native or Motion, this means that not every individual Element inside of it animates its position. This can lead to better performance and a more continuous feeling, smooth animation compared to animating every individual piece. However, it can also lose continuity in things that should be moving by themselves. So you might have to add more `` boundaries manually as a result. -- Many users may prefer not having animations on the page. React doesn't automatically disable animations for this case. We recommend that using the `@media (prefers-reduced-motion)` media query to disable animations or tone them down based on user preference. In the future, CSS libraries may have this built-in to their presets. -- Currently, `` only works in the DOM. We're working on adding support for React Native and other platforms. +- По умолчанию обновления `setState` происходят немедленно и не активируют ``, только обновления, обернутые в [Transition](/reference/react/useTransition). Вы также можете использовать [``](/reference/react/Suspense), чтобы включиться в Transition для [отображения контента](/link-to-suspense-below). +- `` создает изображение, которое можно перемещать, масштабировать и перекрестно перекрывать. В отличие от Layout Animations, которые вы могли видеть в React Native или Motion, это означает, что не каждый отдельный Element внутри него анимирует свою позицию. Это может привести к лучшей производительности и более непрерывному ощущению, плавной анимации по сравнению с анимацией каждой отдельной части. Однако это также может привести к потере непрерывности в вещах, которые должны двигаться сами по себе. В результате вам, возможно, придется вручную добавить больше границ ``. +- Многие пользователи могут предпочесть отсутствие анимации на странице. React не отключает анимацию автоматически для этого случая. Мы рекомендуем использовать медиа-запрос `@media (prefers-reduced-motion)`, чтобы отключить анимацию или уменьшить ее в зависимости от предпочтений пользователя. В будущем библиотеки CSS могут иметь это встроенным в свои предустановки. +- В настоящее время `` работает только в DOM. Мы работаем над добавлением поддержки React Native и других платформ. --- +## Использование {/*usage*/} -## Usage {/*usage*/} - -### Animating an element on enter/exit {/*animating-an-element-on-enter*/} +### Анимация элемента при входе/выходе {/*animating-an-element-on-enter*/} -Enter/Exit Transitions trigger when a `` is added or removed by a component in a transition: +Переходы Enter/Exit срабатывают, когда `` добавляется или удаляется компонентом в переходе: ```js function Child() { @@ -171,9 +168,9 @@ function Parent() { } ``` -When `setShow` is called, `show` switches to `true` and the `Child` component is rendered. When `setShow` is called inside `startTransition`, and `Child` renders a `ViewTransition` before any other DOM nodes, an `enter` animation is triggered. +Когда вызывается `setShow`, `show` переключается на `true`, и компонент `Child` отображается. Когда `setShow` вызывается внутри `startTransition`, и `Child` отображает `ViewTransition` перед любыми другими узлами DOM, запускается анимация `enter`. -When `show` switches back to `false`, an `exit` animation is triggered. +Когда `show` переключается обратно на `false`, запускается анимация `exit`. @@ -252,7 +249,6 @@ export default [ ] ``` - ```css #root { display: flex; @@ -348,7 +344,7 @@ button:hover { -`` only activates if it is placed before any DOM node. If `Child` instead looked like this, no animation would trigger: +`` активируется только в том случае, если он расположен перед любым узлом DOM. Если `Child` вместо этого выглядел так, анимация не сработает: ```js [3, 5] function Component() { @@ -363,9 +359,9 @@ function Component() { --- -### Animating a shared element {/*animating-a-shared-element*/} +### Анимация общего элемента {/*animating-a-shared-element*/} -Normally, we don't recommend assigning a name to a `` and instead let React assign it an automatic name. The reason you might want to assign a name is to animate between completely different components when one tree unmounts and another tree mounts at the same time. To preserve continuity. +Обычно мы не рекомендуем назначать имя для ``, а вместо этого позволять React назначать ему автоматическое имя. Причина, по которой вы можете захотеть назначить имя, заключается в том, чтобы анимировать между совершенно разными компонентами, когда одно дерево размонтируется, а другое дерево монтируется одновременно. Чтобы сохранить непрерывность. ```js @@ -373,11 +369,11 @@ Normally, we don't recommend assigning a name to a `` and instea ``` -When one tree unmounts and another mounts, if there's a pair where the same name exists in the unmounting tree and the mounting tree, they trigger the "share" animation on both. It animates from the unmounting side to the mounting side. +Когда одно дерево размонтируется, а другое монтируется, если есть пара, в которой одно и то же имя существует в размонтируемом дереве и в монтируемом дереве, они запускают анимацию "share" на обоих. Он анимируется со стороны размонтирования на сторону монтирования. -Unlike an exit/enter animation this can be deeply inside the deleted/mounted tree. If a `` would also be eligible for exit/enter, then the "share" animation takes precedence. +В отличие от анимации выхода/входа, это может быть глубоко внутри удаленного/смонтированного дерева. Если `` также будет иметь право на выход/вход, то анимация "share" имеет приоритет. -If Transition first unmounts one side and then leads to a `` fallback being shown before eventually the new name being mounted, then no shared element transition happens. +Если Transition сначала размонтирует одну сторону, а затем приводит к отображению резервного варианта ``, прежде чем, в конечном итоге, будет смонтировано новое имя, то переход общего элемента не произойдет. @@ -591,20 +587,19 @@ button:hover { - -If either the mounted or unmounted side of a pair is outside the viewport, then no pair is formed. This ensures that it doesn't fly in or out of the viewport when something is scrolled. Instead it's treated as a regular enter/exit by itself. +Если какая-либо сторона пары (смонтированная или размонтированная) находится за пределами области просмотра, то пара не формируется. Это гарантирует, что она не будет влетать или вылетать из области просмотра при прокрутке чего-либо. Вместо этого это рассматривается как обычный вход/выход само по себе. -This does not happen if the same Component instance changes position, which triggers an "update". Those animate regardless if one position is outside the viewport. +Это не произойдет, если один и тот же экземпляр Component изменяет положение, что запускает "update". Они анимируются независимо от того, находится ли одна позиция за пределами области просмотра. -There's currently a quirk where if a deeply nested unmounted `` is inside the viewport but the mounted side is not within the viewport, then the unmounted side animates as its own "exit" animation even if it's deeply nested instead of as part of the parent animation. +В настоящее время существует причуда, когда, если глубоко вложенный размонтированный `` находится внутри области просмотра, но смонтированная сторона не находится в области просмотра, то размонтированная сторона анимируется как собственная анимация "exit", даже если она глубоко вложена, а не как часть родительской анимации. -It's important that there's only one thing with the same name mounted at a time in the entire app. Therefore it's important to use unique namespaces for the name to avoid conflicts. To ensure you can do this you might want to add a constant in a separate module that you import. +Важно, чтобы в приложении одновременно было смонтировано только одно имя с одним и тем же именем. Поэтому важно использовать уникальные пространства имен для имени, чтобы избежать конфликтов. Чтобы убедиться, что вы можете это сделать, вы можете добавить константу в отдельный модуль, который вы импортируете. ```js export const MY_NAME = "my-globally-unique-name"; @@ -618,16 +613,15 @@ import {MY_NAME} from './shared-name'; --- -### Animating reorder of items in a list {/*animating-reorder-of-items-in-a-list*/} - +### Анимация переупорядочения элементов в списке {/*animating-reorder-of-items-in-a-list*/} ```js items.map(item => ) ``` -When reordering a list, without updating the content, the "update" animation triggers on each `` in the list if they're outside a DOM node. Similar to enter/exit animations. +При переупорядочении списка без обновления содержимого анимация "update" запускается для каждого `` в списке, если они находятся за пределами узла DOM. Аналогично анимации входа/выхода. -This means that this will trigger the animation on this ``: +Это означает, что это запустит анимацию на этом ``: ```js function Component() { @@ -637,7 +631,7 @@ function Component() { ```js src/Video.js hidden -function Thumbnail({ video }) { +function Thumbnail({ video, children }) { return (