跳转到正文

快速入门

GitHub

你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下 prompt:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-native-navigation` plugin in my project.

如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:

  1. 安装软件包

    终端窗口
    npm i @capgo/capacitor-native-navigation
  2. 同步原生项目

    终端窗口
    npx cap sync
  3. 配置原生界面外壳

    import { NativeNavigation } from '@capgo/capacitor-native-navigation';
    await NativeNavigation.configure({
    contentInsetMode: 'css',
    animationDuration: 360,
    colors: {
    tint: '#0f172a',
    inactiveTint: '#64748b',
    },
    });
  4. 渲染原生导航栏

    await NativeNavigation.setNavbar({
    title: 'Home',
    subtitle: 'Native chrome',
    transparent: true,
    backButton: { visible: false },
    rightItems: [
    {
    id: 'compose',
    title: 'Compose',
    icon: {
    svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',
    },
    },
    ],
    });
  5. 渲染原生标签栏

    await NativeNavigation.setTabbar({
    selectedId: 'home',
    labelVisibilityMode: 'selected',
    icons: true,
    colors: {
    dynamic: true,
    tint: '#0f172a',
    inactiveTint: '#64748b',
    },
    tabs: [
    {
    id: 'home',
    title: 'Home',
    icon: {
    svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 10v10h14V10"/></svg>',
    },
    },
    {
    id: 'settings',
    title: 'Settings',
    badge: '2',
    icon: {
    svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>',
    },
    },
    ],
    });
  6. 处理原生 Intent 事件

    await NativeNavigation.addListener('navbarBack', () => {
    router.back();
    });
    await NativeNavigation.addListener('navbarItemTap', ({ id }) => {
    if (id === 'compose') router.push('/compose');
    });
    await NativeNavigation.addListener('tabSelect', ({ id }) => {
    router.push(`/${id}`);
    });

传入 segments 改为 setNavbar 在导航栏下方堆叠多行原生 segment,例如顶层是 scope 切换器,下方是 section 标签页。各行从上到下绘制,每一行都会为 navbar 和上报的 insets 增加 44pt (iOS) 或 48dp (Android)。iOS 使用 UISegmentedControl 以及玻璃胶囊;Android 使用 Material 分段按钮和 filter chips。

iOSAndroid
iOS 录屏:点击 Account 分区,切换到 Organization 后,第二行会换成八个可滚动的 chips,再选择 BillingAndroid 录屏:Account / Organization 分段行位于可滚动的 section chips 上方,切换 scope 并选择 Billing
const sections = {
account: ['General', 'Notifications', 'Password', 'Two-factor'],
organization: ['General', 'Members', 'Plans', 'Usage', 'Credits', 'Billing', 'Security', 'Webhooks'],
};
const selection = { scope: 'account', section: 'general' };
const renderNavbar = () =>
NativeNavigation.setNavbar({
title: 'Settings',
segments: [
{
id: 'scope',
selectedId: selection.scope,
items: [
{ id: 'account', title: 'Account' },
{ id: 'organization', title: 'Organization' },
],
},
{
id: 'section',
style: 'scroll', // scrolling chips; `auto` uses `segmented` for up to 4 items
selectedId: selection.section,
items: sections[selection.scope].map((title) => ({ id: title.toLowerCase(), title })),
},
],
});
await NativeNavigation.addListener('navbarSegmentSelect', async ({ groupId, id }) => {
if (groupId === 'scope') {
selection.scope = id;
selection.section = 'general'; // the second level depends on the first one
} else {
selection.section = id;
}
await renderNavbar();
});
await renderNavbar();

用户点击时,选中状态会原生切换,但每次 setNavbar 调用都会重新应用 selectedId 。请将选中的 ids 保留在 state 中,并在之后每次 setNavbar 调用时传入;若要取消选中,请发送上一次的 selectedId。Item 还接受 icon, accessibilityLabel,以及 enabled。传入 segments: [] 用于移除这些行。自 8.13.0 起可用。

原生转场是围绕常规 JavaScript 路由变更的一层事务:

const transition = await NativeNavigation.beginTransition({
direction: 'forward',
});
router.push('/detail');
await router.ready?.();
await NativeNavigation.setNavbar({
title: 'Detail',
backButton: { visible: true, title: 'Back' },
});
await NativeNavigation.finishTransition({
id: transition.id,
direction: 'forward',
});

在卡片到详情页或媒体预览流程中使用缩放辅助函数。在路由切换内容前传入被点击的元素,然后在详情页就绪后结束。

import { beginZoomTransition, finishZoomTransition } from '@capgo/capacitor-native-navigation';
const card = document.querySelector('[data-message-card]');
if (card) {
const transition = await beginZoomTransition(card, { cornerRadius: 18 });
router.push('/message/42');
await router.ready?.();
await NativeNavigation.setNavbar({
title: 'Message',
backButton: { visible: true, title: 'Inbox' },
});
await finishZoomTransition(undefined, {
id: transition.id,
cornerRadius: 18,
});
}

使用 Native Navigation 处理原生 navbar、tabbar、safe-area insets 和原生 Intent 事件。使用 @capgo/capacitor-transitions 来管理原生外壳下的 WebView 页面栈。

终端窗口
npm install @capgo/capacitor-native-navigation @capgo/capacitor-transitions
npx cap sync

初始化这两个包:

import { NativeNavigation } from '@capgo/capacitor-native-navigation';
import '@capgo/capacitor-transitions';
import { initTransitions, setupRouterOutlet, setDirection } from '@capgo/capacitor-transitions/react';
initTransitions({ platform: 'auto' });
const outlet = document.querySelector('cap-router-outlet');
if (outlet) {
setupRouterOutlet(outlet, { platform: 'auto', swipeGesture: 'auto' });
}
await NativeNavigation.configure({
contentInsetMode: 'css',
});

保留 cap-router-outlet 专注于页面,而非重复的 Web 栏:

<cap-router-outlet platform="auto" swipe-gesture="auto">
<cap-page>
<cap-content slot="content" fullscreen>
<main class="page">Inbox content</main>
</cap-content>
</cap-page>
</cap-router-outlet>

用同一套 router actions 驱动两个包:

async function openMessage(id: string) {
setDirection('forward');
await router.push(`/messages/${id}`);
await NativeNavigation.setNavbar({
title: 'Message',
backButton: { visible: true, title: 'Inbox' },
});
}
await NativeNavigation.addListener('navbarBack', () => {
setDirection('back');
router.back();
});
await NativeNavigation.addListener('tabSelect', ({ id }) => {
setDirection('root');
router.push(`/${id}`);
});

每次路由切换只选一个动画层。让 @capgo/capacitor-transitions 为常规页面推送添加动画,仅在共享元素或缩放路由中使用 Native Navigation 的缩放辅助功能。

使用 contentInsetMode: 'css',该插件会将原生栏尺寸写入 document.documentElement.

.page {
padding-top: var(--cap-native-navigation-top);
padding-bottom: var(--cap-native-navigation-bottom);
}

可用变量:

  • --cap-native-navigation-top
  • --cap-native-navigation-right
  • --cap-native-navigation-bottom
  • --cap-native-navigation-left
  • --cap-native-navbar-height
  • --cap-native-tabbar-height

由于原生 UI 负责渲染图标,图标必须可序列化。您可以使用跨平台 SVG、特定平台的 SVG、SF Symbols、捆绑的 iOS 图像、Android drawable 资源或捆绑的 Android 图像。

const icon = {
svg: '<svg viewBox="0 0 24 24"><path d="M3 10.5 12 3l9 7.5"/></svg>',
width: 24,
height: 24,
template: true,
src: 'fallback_asset_name',
ios: {
svg: '<svg viewBox="0 0 24 24"><path d="M3 10.5 12 3l9 7.5"/></svg>',
sfSymbol: 'house.fill',
image: 'BundledAssetName',
},
android: {
svg: '<svg viewBox="0 0 24 24"><path d="M3 10.5 12 3l9 7.5"/></svg>',
resource: 'ic_menu_view',
image: 'bundled_drawable_name',
},
};

内联 SVG 支持 Lucide 和 Feather 等常见图标集使用的图标专用子集: path, line, polyline, polygon, circle,以及 rect。SVG 图标默认作为模板图像渲染,因此原生着色颜色可以重新着色它们。

该包可以注册自定义元素,以实现与框架无关的声明式配置:

import { defineNativeNavigationElements } from '@capgo/capacitor-native-navigation';
defineNativeNavigationElements();
<cap-native-navigation-provider enabled="true" content-inset-mode="css"></cap-native-navigation-provider>
<cap-native-navbar
title="Home"
transparent
right-items='[{"id":"compose","title":"Compose","icon":{"svg":"<svg viewBox=\"0 0 24 24\"><path d=\"M12 20h9\"/></svg>"}}]'
></cap-native-navbar>
<cap-native-tabbar
selected-id="home"
tabs='[{"id":"home","title":"Home","icon":{"ios":{"sfSymbol":"house.fill"}}}]'
></cap-native-tabbar>

在 iPhone Duo 上,iOS 通常会将系统标签栏和状态栏置于 垂直侧边栏. env(safe-area-inset-top) 可以 0 而 left 或 right 增长。设置 viewport-fit=cover 当你在应用任意位置用 CSS env 设置内边距时,注意 viewport meta 标签。在 Xcode Device Hub 中测试折叠、展开、横屏和 Split View 形态。

Native Navigation 使用真实的 UINavigationBar 以及 UITabBar,因此 系统 tab bar 跟随侧边栏。该 曲线 tab bar 形状保持在底部;窗口变宽时,中心操作按钮仍保留圆形底座。

两种展开的横屏布局。左侧,系统 tab bar 位于侧边栏;右侧,曲线 tab bar 沿底部排列,中心操作按钮位于圆形底座中。

使用 contentInsetMode: 'css',用插件变量为 Web 内容设置内边距。使用 max() 并为每个边缘设置 env 回退,确保插件变量缺失时布局仍然正确。 0 无需累加重复的内边距:

main {
padding-top: max(var(--cap-native-navigation-top, 0px), env(safe-area-inset-top, 0px));
padding-right: max(var(--cap-native-navigation-right, 0px), env(safe-area-inset-right, 0px));
padding-bottom: max(var(--cap-native-navigation-bottom, 0px), env(safe-area-inset-bottom, 0px));
padding-left: max(var(--cap-native-navigation-left, 0px), env(safe-area-inset-left, 0px));
}

监听 safeAreaChanged (或 capNativeNavigation:safeAreaChanged 开启 window) 当侧边栏或折叠状态发生变化时。对于托管的系统标签栏, insets.tabbarHeight 可能为 0 以避免底部双重内边距;使用 insets.systemTabbarHeight 或 --cap-native-system-tabbar-height 用于 FAB 偏移量。

Capacitor 宽度指南(viewport-fit、系统栏、状态栏、测试): 在 Capacitor 应用中支持 iPhone Duo.

  • iOS 渲染 UINavigationBar 以及 UITabBar;iOS 26+ 使用系统 Liquid Glass 栏行为。
  • Android 渲染 AppCompat 工具栏和 Material 底部导航。
  • Web 回退方案不绘制原生栏。它镜像事件和 inset 变量,用于浏览器开发。
  • 该插件保持一个全屏 Capacitor WebView。原生层负责框架、栏、安全区域报告和过渡外壳。

如果你正在使用 快速入门 来规划原生媒体和界面行为,并将其与 使用 @capgo/capacitor-native-navigation 关于“使用 @capgo/capacitor-native-navigation”中的原生能力, 使用 @capgo/capacitor-live-activities 用于使用 @capgo/capacitor-live-activities 时的原生能力, @capgo/capacitor-live-activities 在 @capgo/capacitor-live-activities 中的实现细节, 使用 @capgo/capacitor-video-player 有关使用 @capgo/capacitor-video-player 时的原生能力,以及 @capgo/capacitor-video-player 关于 @capgo/capacitor-video-player. 中的实现细节