Communitygithub.com

React 檢視轉場動畫指南

使用 React 的 View Transition API 實作流暢、原生風格的動畫,支援頁面轉場、共享元素動畫、列表重排與狀態變更。

React 檢視轉場動畫指南 是什麼?

這份技能指南專注於如何使用 React 的 `<ViewTransition>` 元件、`startTransition`、`useDeferredValue` 及 Suspense,搭配瀏覽器原生 `document.startViewTransition` API 來實作無縫的 UI 轉場動畫。它提供了一個優先級框架來決定何時使用何種動畫模式(共享元素、資料載入、列表變動、元件進出、路由變更),並詳細說明 CSS 偽元素與轉場類型(如 `nav-forward`、`nav-back`)的搭配方式。技能涵蓋了在 Next.js App Router(無需額外安裝)與純 React 專案(需 `react@canary`)中的整合方式,並強調 `default="none"` 的設定以避免不必要的動畫干擾。此外,還提供了共享元素、列表身分、Suspense 揭示、方向性導覽等實際模式範例,以及無障礙的低動畫設定。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/xzedm/clipplic-landing/tree/HEAD/.agents/skills/vercel-react-view-transitions

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

預覽

來自技能 README

React 檢視轉場動畫指南 preview
React 檢視轉場動畫指南 preview

說明文件

React 檢視轉場動畫

使用瀏覽器原生的 document.startViewTransition 在 UI 狀態之間製作動畫。使用 <ViewTransition> 宣告什麼,使用 startTransition / useDeferredValue / Suspense 觸發何時,使用 CSS 類別控制如何。不支援的瀏覽器會優雅降級,跳過動畫。

何時製作動畫

每個 <ViewTransition> 都應傳達空間關係或連續性。如果你無法說清楚它傳達了什麼,就不要加入它。

請依照以下順序,實作此清單中所有適用的模式:

優先級模式傳達的意義
1共享元素 (name)"相同的東西,更深入"
2Suspense 揭示"資料已載入"
3列表身分 (每個項目 key)"相同項目,新排列"
4狀態變更 (enter/exit)"某個東西出現/消失"
5路由變更 (佈局層級)"前往新的地方"

這是一個實作順序,不是一個「挑選一個」的清單。實作所有適合該應用程式的模式。只有當應用程式完全沒有該模式的使用案例時,才跳過它。

選擇動畫風格

情境動畫原因
階層式導覽(列表 → 詳細)類型鍵控 nav-forward / nav-back傳達空間深度
橫向導覽(分頁到分頁)裸 <ViewTransition>(淡入淡出)或 default="none"沒有深度需要傳達
Suspense 揭示enter/exit 字串屬性內容到達
重新驗證 / 背景更新default="none"靜默,不需要動畫

保留方向性滑動給階層式導覽(列表 → 詳細)和有順序的序列(上一張/下一張照片、輪播、分頁結果)。對於有序序列,方向傳達位置:「下一張」從右側滑入,「上一張」從左側滑入。橫向/無序的導覽(分頁到分頁)不應使用方向性滑動。它會錯誤地暗示空間深度。


可用性

  • Next.js: 不要安裝 react@canary:App Router 已在內部捆綁 React canary。ViewTransition 可直接使用。npm ls react 可能會顯示一個看起來穩定的版本;這是預期的行為。
  • 沒有 Next.js 的情況: 安裝 react@canary react-dom@canary(ViewTransition 不在穩定的 React 中)。
  • 瀏覽器支援:Chromium 111+、Firefox 144+、Safari 18.2+。在不支援的瀏覽器上優雅降級。

實作工作流程

在為現有應用程式加入檢視轉場時,請逐步遵循 references/implementation.md。從審查開始,不要跳過它。將 references/css-recipes.md 中的 CSS 配方複製到全域樣式表中,不要自己撰寫動畫 CSS。


核心概念

<ViewTransition> 元件

import { ViewTransition } from 'react';

<ViewTransition>
  <Component />
</ViewTransition>

React 會自動指派一個唯一的 view-transition-name 並在幕後呼叫 document.startViewTransition。永遠不要自己呼叫 startViewTransition。

動畫觸發器

觸發器觸發時機
enter在轉場期間,<ViewTransition> 首次被插入時
exit在轉場期間,<ViewTransition> 首次被移除時
update<ViewTransition> 內部的 DOM 發生變更時。對於巢狀 VT,變更套用於最內層的 VT
share當一個具名的 VT 卸載,且另一個具有相同 name 的 VT 在同一個轉場中載入時

只有 startTransition、useDeferredValue 或 Suspense 能啟用 VT。一般的 setState 不會觸發動畫。

關鍵放置規則

<ViewTransition> 只有在它出現在任何 DOM 節點之前時,才能啟用 enter/exit:

// 可行
<ViewTransition enter="auto" exit="auto">
  <div>內容</div>
</ViewTransition>

// 損壞,div 包裹了 VT,抑制了 enter/exit
<div>
  <ViewTransition enter="auto" exit="auto">
    <div>內容</div>
  </ViewTransition>
</div>

使用檢視轉場類別設定樣式

屬性

值:"auto"(瀏覽器交叉淡入淡出)、"none"(停用)、"class-name"(自訂 CSS)或 { [type]: value } 用於特定類型的動畫。

<ViewTransition default="none" enter="slide-in" exit="slide-out" share="morph" />

如果 default 是 "none",則所有觸發器都是關閉的,除非明確列出。

CSS 偽元素

  • ::view-transition-old(.class):舊的快照
  • ::view-transition-new(.class):新的快照
  • ::view-transition-group(.class):容器
  • ::view-transition-image-pair(.class):新舊圖像配對

請參閱 references/css-recipes.md 以取得現成可用的動畫配方。


轉場類型

使用 addTransitionType 為轉場加上標籤,以便 VT 可以根據上下文選擇不同的動畫。多次呼叫以堆疊類型,樹中的不同 VT 會對不同的類型做出反應:

startTransition(() => {
  addTransitionType('nav-forward');
  addTransitionType('select-item');
  router.push('/detail/1');
});

傳遞一個物件將類型對應到 CSS 類別。適用於 enter、exit 和 share:

<ViewTransition
  enter={{ 'nav-forward': 'slide-from-right', 'nav-back': 'slide-from-left', default: 'none' }}
  exit={{ 'nav-forward': 'slide-to-left', 'nav-back': 'slide-to-right', default: 'none' }}
  share={{ 'nav-forward': 'morph-forward', 'nav-back': 'morph-back', default: 'morph' }}
  default="none"
>
  <Page />
</ViewTransition>

enter 和 exit 不必對稱。例如,淡入但方向性地滑出:

<ViewTransition
  enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }}
  exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
  default="none"
>

TypeScript: ViewTransitionClassPerType 在物件中需要一個 default 鍵。

對於具有多個頁面的應用程式,將類型鍵控的 VT 提取為可複用的包裝組件:

export function DirectionalTransition({ children }: { children: React.ReactNode }) {
  return (
    <ViewTransition
      enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
      exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
      default="none"
    >
      {children}
    </ViewTransition>
  );
}

router.back() 和瀏覽器返回按鈕

router.back() 和瀏覽器的返回/前進按鈕不會觸發檢視轉場(popstate 是同步的,與 startViewTransition 不相容)。請改用帶有明確 URL 的 router.push()。

類型與 Suspense

類型在導覽期間可用,但不能在後續的 Suspense 揭示期間使用(獨立的轉場,沒有類型)。對於頁面層級的 enter/exit,請使用類型映射;對於 Suspense 揭示,請使用簡單的字串屬性。


共享元素轉場

兩個 VT 使用相同的 name,一個卸載,一個載入,會建立一個共享元素的變形效果:

<ViewTransition name="hero-image">
  <img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} />
</ViewTransition>

// 在另一個視圖上,相同名稱
<ViewTransition name="hero-image">
  <img src="/full.jpg" />
</ViewTransition>
  • 給定 name 的 VT 一次只能有一個被載入。請使用唯一的名稱(photo-${id})。注意可複用的組件:如果一個具有命名 VT 的元件同時在 modal/popover 和 頁面中渲染,兩者會同時載入並破壞變形效果。請透過 prop 使名稱成為條件式,或者將命名的 VT 移出共享元件,放入特定的消費者中。
  • share 優先於 enter/exit。仔細思考每個導覽路徑:當沒有形成匹配的配對時(例如,目標頁面沒有相同的名稱),enter/exit 會觸發。考慮該元素是否需要為這些路徑提供一個備用動畫。
  • 永遠不要在具有共享變形效果的頁面上使用淡出退出。請改用方向性滑動。

常見模式

Enter/Exit

{show && (
  <ViewTransition enter="fade-in" exit="fade-out"><Panel /></ViewTransition>
)}

列表重排

{items.map(item => (
  <ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition>
))}

在 startTransition 內部觸發。避免在列表和 VT 之間使用包裝 <div>。

組合共享元素與列表身分

共享元素和列表身分是獨立的關注點,不要將兩者混淆。當一個列表項目包含共享元素(例如,一個變形為詳細檢視的圖片)時,請使用兩個巢狀的 <ViewTransition> 邊界:

{items.map(item => (
  <ViewTransition key={item.id}>                                      {/* 列表身分 */}
    <Link href={`/items/${item.id}`}>
      <ViewTransition name={`item-image-${item.id}`} share="morph">   {/* 共享元素 */}
        <Image src={item.image} />
      </ViewTransition>
      <p>{item.name}</p>
    </Link>
  </ViewTransition>
))}

外層 VT 處理列表重排/進入動畫。內層 VT 處理跨路由的共享元素變形。缺少任何一層都意味著該動畫會悄悄地被忽略。

使用 key 強制重新進入

<ViewTransition key={searchParams.toString()} enter="slide-up" default="none">
  <ResultsGrid />
</ViewTransition>

注意: 如果包裹了 <Suspense>,變更 key 會重新載入邊界並重新擷取資料。

Suspense 過渡到內容

簡單的交叉淡入淡出:

<ViewTransition>
  <Suspense fallback={<Skeleton />}><Content /></Suspense>
</ViewTransition>

方向性揭示:

<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
  <ViewTransition enter="slide-up" default="none"><Content /></ViewTransition>
</Suspense>

更多模式,請參閱 references/patterns.md。


多個 VT 如何互動

每個匹配觸發器的 VT 會在單一 document.startViewTransition 中同時觸發。處於不同轉場(導覽與後續 Suspense 解析)中的 VT 不會互相競爭。

廣泛使用 default="none"

沒有它,每個 VT 都會在每次轉場時觸發瀏覽器交叉淡入淡出。Suspense 解析、useDeferredValue 更新、背景重新驗證皆是如此。始終使用 default="none",並僅明確啟用所需的觸發器。

兩種模式共存

模式 A. 方向性滑動: 每個頁面上的類型鍵控 VT,在導覽期間觸發。 模式 B. Suspense 揭示: 簡單的字串屬性,在資料載入時觸發(無類型)。

因為它們在不同的時刻觸發,所以可以共存。兩者都設 default="none" 可以防止交叉干擾。始終將 enter 與 exit 配對。將方向性 VT 放在頁面組件中,而不是佈局中。

巢狀 VT 限制

當父層 VT 退出時,內部的巢狀 VT 不會觸發它們自己的 enter/exit,只有最外層的 VT 會執行動畫。在頁面導覽期間,無法實現逐項的 stagger 動畫。請參閱 react#36135 以了解實驗性的選擇性修正。


Next.js 整合

有關 Next.js 設定(experimental.viewTransition 標誌、next/link 上的 transitionTypes prop、App Router 模式、Server Components),請參閱 references/nextjs.md。


無障礙

始終將 references/css-recipes.md 中的減少動畫 CSS 加入您的全域樣式表中。


參考檔案

  • references/implementation.md:逐步實作工作流程。
  • references/patterns.md:模式、動畫時機、事件 API、疑難排解。
  • references/css-recipes.md:現成可用的 CSS 動畫配方。
  • references/nextjs.md:Next.js App Router 模式和 Server Component 細節。

完整編譯文件

包含所有展開的參考檔案的完整指南:AGENTS.md

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

xzedm/clipplic-landing

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

xzedm/clipplic-landing

Material Design 3 and Android platform guidelines. Use when building Android apps with Jetpack Compose or XML layouts, implementing Material You, navigation, or accessibility. Triggers on tasks involving Android UI, Compose components, dynamic color, or Material Design compliance.

xzedm/clipplic-landing

Apple's approach to interface design and fluid, physical motion, translated for the web. Use when building or reviewing gesture-driven UI, spring animations, drag/swipe/sheet interactions, momentum and interruptible transitions, translucent materials and depth, typography (optical sizing, tracking, leading), reduced-motion, or the design foundations (feedback, spatial consistency, restraint) behind Apple-style interfaces.

xzedm/clipplic-landing

Design iOS apps following Apple's Human Interface Guidelines. Generate native components, validate designs, and ensure accessibility compliance for iPhone, iPad, and Apple Watch.

xzedm/clipplic-landing

Redesign mobile app UI to feel unmistakably Apple-like, iOS-forward, and native. Use this skill when building iOS apps, applying Apple Human Interface Guidelines, or creating native-feeling mobile interfaces with SF Pro typography, translucency, and system-like components.

xzedm/clipplic-landing

Accessibility engineering for product interfaces, from focus states and keyboard support to ARIA, forms, and screen readers. Use when building or reviewing UI components, modals, menus, forms, custom widgets, or when the user says "make this accessible" or reports keyboard or screen-reader issues. Triggers on accessibility, a11y, WCAG, aria, focus ring, focus-visible, focus trap, keyboard navigation, tab order, tabindex, screen reader, sr-only, aria-live, alt text, hit area, touch target, prefers-reduced-motion, autoplay, toast duration, skip link, semantic HTML, aria-label, form errors, disabled buttons, "not keyboard accessible".

xzedm/clipplic-landing

OKLCH color space and color usage for web projects. Convert hex/rgb/hsl to oklch, generate palettes, check contrast, handle gamut boundaries, theme with Tailwind v4, and apply color with meaning. Triggers on oklch, color conversion, palette generation, contrast ratio, gamut, display p3, design tokens, semantic color tokens, hue drift, chroma, dark mode colors, accent color, color meaning, light and dark appearance, increased contrast.

xzedm/clipplic-landing

Layout structure for web interfaces, from grouping and alignment to reading order, progressive disclosure, and adaptive breakpoints. Use when structuring a page or component, spacing or aligning controls, deciding what collapses at small sizes, handling RTL layout direction, or reviewing frontend code for layout. Triggers on layout, spacing, alignment, grouping, negative space, whitespace, visual hierarchy, reading order, progressive disclosure, breakpoints, responsive layout, container queries, safe area, full-bleed, edge-to-edge, layout margins, RTL layout, logical properties.

xzedm/clipplic-landing

Web typography from choosing fonts to spacing, wrapping and accessibility. Use when picking or pairing typefaces, configuring variable fonts or OpenType features, setting up a type scale, checking heading hierarchy, styling text in components, truncating text, styling underlines, selection, placeholders or carets, or reviewing frontend code for typography. Triggers on typography, fonts, font formats, woff2, variable fonts, font-weight, opentype, font-feature-settings, letter-spacing, line-height, type scale, heading hierarchy, heading levels, tabular numbers, text-wrap, truncation, line clamp, underlines, text-decoration, text selection, iOS input zoom, scaled input text, font smoothing, text contrast, measure, line length, text-box, smart punctuation, drop cap.

xzedm/clipplic-landing

Design engineering principles for making interfaces feel polished. Use when building UI components, reviewing frontend code, implementing animations, hover states, shadows, borders, micro-interactions, enter/exit animations, choosing or reviewing icons, or any visual detail work. Triggers on UI polish, design details, "make it feel better", "feels off", stagger animations, border radius, optical alignment, image outlines, box shadows, icons, icon stroke weight, icon states, motion restraint.

xzedm/clipplic-landing

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

xzedm/clipplic-landing

Generate developer handoff specs from a design. Use when a design is ready for engineering and needs a spec sheet covering layout, design tokens, component props, interaction states, responsive breakpoints, edge cases, and animation details.

xzedm/clipplic-landing

This skill encodes Emil Kowalski's philosophy on UI polish, component design, animation decisions, and the invisible details that make software feel great.

xzedm/clipplic-landing

Extract design primitives from a public website and generate starter token files for your project.

xzedm/clipplic-landing

Use this skill alongside figma-use when the task involves translating an application page, view, or multi-section layout into Figma. Triggers: 'write to Figma', 'create in Figma from code', 'push page to Figma', 'take this app/page and build it in Figma', 'create a screen', 'build a landing page in Figma', 'update the Figma screen to match code', 'convert this modal/dialog/drawer/panel to Figma'. This is the preferred workflow skill whenever the user wants to build or update a full page, modal, dialog, drawer, sidebar, panel, or any composed multi-section view in Figma from code or a description. Discovers design system components, variables, and styles from Code Connect files, existing screens, and library search, then imports them and assembles views incrementally section-by-section using design system tokens instead of hardcoded values.

xzedm/clipplic-landing

**MANDATORY prerequisite**: you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context, e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.

xzedm/clipplic-landing

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

xzedm/clipplic-landing

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications.

xzedm/clipplic-landing

Elite UX/UI & Advanced GSAP Motion Engineer. Enforces Python-driven true randomization for layout variance, strict AIDA page structure, wide editorial typography (bans 6-line wraps), gapless bento grids, strict GSAP ScrollTriggers (pinning, stacking, scrubbing), inline micro-images, and massive section spacing.

xzedm/clipplic-landing

Fast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)

相關技能