指南
原生导航教程
使用@capgo/native-navigation
@capgo/native-navigation Capacitor WebView下渲染原生顶部导航栏、底部标签栏和路由转场壳。您的web框架仍然控制路由和内容,而原生则控制应用框架。
安装并同步
bun add @capgo/native-navigation
bunx cap sync
配置原生框架
import { NativeNavigation } from '@capgo/native-navigation';
await NativeNavigation.configure({
contentInsetMode: 'css',
animationDuration: 360,
colors: {
tint: '#0f172a',
inactiveTint: '#64748b',
},
});
渲染原生导航栏
await NativeNavigation.setNavbar({
title: 'Inbox',
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>',
},
},
],
});
渲染原生标签栏
await NativeNavigation.setTabbar({
selectedId: 'inbox',
labels: true,
icons: true,
tabs: [
{
id: 'inbox',
title: 'Inbox',
icon: {
svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4h16v16H4z"/><path d="m4 13 4 4h8l4-4"/></svg>',
},
},
{
id: 'search',
title: 'Search',
icon: {
svg: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></svg>',
},
},
],
});
将原生事件连接到您的路由器
原生导航发射意图。您的路由器仍然执行路由更改:
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}`);
});
动画路由更改
在您的正常 Web 路由更新周围使用一个过渡事务:
const transition = await NativeNavigation.beginTransition({
direction: 'forward',
});
router.push('/message/42');
await router.ready?.();
await NativeNavigation.setNavbar({
title: 'Message',
backButton: { visible: true, title: 'Inbox' },
});
await NativeNavigation.finishTransition({
id: transition.id,
direction: 'forward',
});
用原生边距填充内容
当 contentInsetMode is css,插件为原生导航栏写入 CSS 变量:
.page {
padding-top: var(--cap-native-navigation-top);
padding-bottom: var(--cap-native-navigation-bottom);
}
图标选择
图标是原生描述符,而不是 React 或 Vue 节点。使用 SVG 时不想打包原生资产时,请使用 SVG:
const icon = {
svg: '<svg viewBox="0 0 24 24"><path d="M3 10.5 12 3l9 7.5"/></svg>',
template: true,
ios: { sfSymbol: 'house.fill' },
android: { resource: 'ic_menu_view' },
};
内联 SVG 支持 path, line, polyline, polygon, circle,和 rect,这涵盖了常见的图标集,如 Lucide 和 Feather。
全参考
- GitHub: https://github.com/Cap-go/capacitor-native-navigation/
- 文档:/docs/plugins/native-navigation/