This tutorial will walk you through crafting a mobile application using React and Capacitor. By the end, you’ll know how to morph a React.js web app into a native mobile application with Capacitor, and add a native feel with Capgo Native Navigation and Transitions.
Capacitor enables the easy transformation of your React.js web app into a native mobile application, requiring no substantial alterations or learning of new strategies such as React Native.
该过程涉及几个简单的步骤。您将很快拥有一个功能齐全的移动应用。因此,请继续阅读本指南。
Capacitor Overview
CapacitorJS 是一个革命性的工具。它可以无缝地与任何 web 项目集成,并将您的应用程序包装在一个原生 webview 中,同时生成 Xcode 和 Android Studio 项目。通过其插件,您可以通过 JS 桥访问原生设备功能,如摄像头。
Capacitor offers a straightforward way to create a native mobile application without any hassle or steep learning curve. Its simple API and streamlined functionality make it easy to incorporate into your project.
设置您的 React.js 应用程序
Let’s go for the simplest method to initiate a React application. We’ll use the npm package manager to create a new React app:
npx create-react-app my-app
为了将我们的项目转换为原生移动应用程序,我们需要一个 export 。我们将在下一刻回来。首先,让我们了解如何将 Capgo 集成到我们的 React 应用程序中。
We’ll come back to this in a moment. First, let’s understand how to integrate Capacitor into our React app.
Integrating Capacitor into Your React.js App
命令。 sync 首先,我们将安装 Capgo CLI 作为开发依赖项,并在我们的项目中设置它。在设置过程中,按“enter”键接受默认值即可。
First, we’ll install the Capacitor CLI as a development dependency and set it up within our project. During the setup, accept the default values for name and bundle ID by pressing “enter.”
接下来,我们将安装核心包和iOS和Android平台相关的包。
最后,我们将添加平台,Capacitor将在项目根目录创建每个平台的文件夹:
# Install the Capacitor CLI locally
npm install -D @capacitor/cli
# Initialize Capacitor in your React project
npx cap init
# Install the required packages
npm install @capacitor/core @capacitor/ios @capacitor/android
# Add the native platforms
npx cap add ios
npx cap add android
The ios 和 context android
目录现在出现在您的React.js项目中。 要访问Android项目,安装Android Studio 。对于iOS,您需要一台Mac,并应安装.
Xcode webDir 在您的 capacitor.config.json 文件中,如下所示:
{
"appId": "com.example.app",
"appName": "my-app",
"webDir": "build",
"bundledWebRuntime": false
}
运行构建命令并同步您的项目与Capacitor:
npm run build
npx cap sync
该命令将构建您的React.js项目,而 npm run build 将使web__CAPGO_KEEP_0__准确地放置在原生平台的正确位置,以便在应用中执行。 npx cap sync will align the web code in the accurate places of the native platforms so they can be executed in an app.
构建和部署原生应用
开发iOS应用需要
Xcode 在您的,并且Android应用也需要 Android Studio。如果您打算在应用商店上发布您的应用,则必须在Apple Developer Program中注册iOS和Google Play Console中的Android。
Capacitor CLI 简化了打开两种本机项目的过程:
npx cap open ios
npx cap open android
一旦您的本机项目设置完成,就可以轻松将应用程序部署到连接的设备上。
对于Android Studio,等待所有内容加载完成,然后将应用程序部署到连接的设备上。
对于Xcode,建立您的签名账户以将应用程序部署到真实设备,而不是仅在模拟器上。完成后,只需点击播放即可在连接的设备上运行应用程序,选择设备的位置在顶部。
如果一切顺利,您将将您的React.js Web应用程序转换为本机移动应用程序!
Capacitor Live Reload
现代开发框架通常都带有热重载功能,幸运的是,您可以在Capacitor中实现相同的功能 但是在您的移动设备上!
您可以通过让Capacitor应用程序从特定URL加载内容来使您的本地托管应用程序在您的网络上可访问并具有实时重载功能。
首先,确定您的本地IP地址。使用Mac,可以通过在终端中运行 ipconfig getifaddr en0 在Windows中,执行 ipconfig 并查找IPv4地址。
然后,指示Capacitor从服务器直接加载应用程序,通过在您的 capacitor.config.ts 文件中添加另一个参数:
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'my-app',
webDir: 'build',
bundledWebRuntime: false,
server: {
url: 'http://192.168.x.xx:3000',
cleartext: true
}
};
export default config;
确保使用准确的IP和端口。运行 npx cap copy 将这些更改应用到我们的本机项目中。
在部署应用程序后再次通过Android Studio或Xcode,任何React应用程序的更改将自动重新加载并在您的应用程序中显示!
请记住,如果安装了新插件,例如摄像头,它需要重新构建您的本机项目。这是因为本机文件已更改,无法在实时更新。
使用Capacitor插件
让我们快速了解如何使用Capacitor插件。让我们安装一个简单的插件,分享插件 Share插件,会弹出原生分享对话框:
npm i @capacitor/share
要使用它,需要导入包并从我们的应用中调用相应的 share() 函数。考虑到 App.js:
import { Share } from '@capacitor/share';
function ShareButton() {
const share = async () => {
await Share.share({
title: 'React App',
text: 'Visit this React App',
url: 'http://localhost:3000',
dialogTitle: 'Share with...'
});
};
return (
<button onClick={share}>
Share
</button>
);
}
export default ShareButton;
安装了新的插件后,记得再次同步你的React项目使用 npx cap sync.
Next, you can make the app feel more native on iOS and Android with Capgo navigation and transitions, and fix common iOS layout issues that cause horizontal overflow or cropped safe areas.
Capgo
原生导航和过渡 原生式UI与 __CAPGO_KEEP_0__ 原生导航和过渡.
For a native mobile feel in a React + Capacitor app, use Capgo plugins instead of web-only UI kits like Konsta UI:
- @capgo/capacitor-native-navigation — 原生导航栏,iOS使用Liquid Glass tab bar,Android使用模糊的tab bar样式。您的React路由器保留了路由状态;插件拥有原生浏览器。
- @capgo/capacitor-transitions — 在WebView层中使用Ionic样式的页面过渡和iOS的边缘滑动返回,未采用Ionic UI。
安装两者:
bun add @capgo/capacitor-native-navigation @capgo/capacitor-transitions
bunx cap sync
配置原生导航以使用CSS inset模式,使Web内容尊严原生栏:
import { NativeNavigation } from '@capgo/capacitor-native-navigation';
await NativeNavigation.configure({
contentInsetMode: 'css',
animationDuration: 360,
glass: {
effect: 'liquidGlass',
},
});
渲染Liquid Glass tab bar(iOS使用系统渲染;Android使用模糊的WebView背景):
await NativeNavigation.setTabbar({
selectedId: 'home',
labelVisibilityMode: 'labeled',
icons: true,
colors: { dynamic: true },
tabs: [
{ id: 'home', title: 'Home', icon: { svg: '...' } },
{ id: 'settings', title: 'Settings', icon: { svg: '...' } },
],
});
await NativeNavigation.addListener('tabSelect', ({ id }) => {
navigate(`/${id}`);
});
在应用壳中添加原生页面过渡:
import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import '@capgo/capacitor-transitions';
import { initTransitions, setDirection, setupRouterOutlet } from '@capgo/capacitor-transitions/react';
initTransitions({ platform: 'auto' });
export function AppShell() {
const navigate = useNavigate();
const outletRef = useRef<HTMLElement>(null);
useEffect(() => {
if (outletRef.current) {
setupRouterOutlet(outletRef.current, { platform: 'auto', swipeGesture: 'auto' });
}
}, []);
const openSettings = () => {
setDirection('forward');
navigate('/settings');
};
return <cap-router-outlet ref={outletRef}>{/* routes */}</cap-router-outlet>;
}
Wrap routed pages in cap-router-outlet, cap-page,和 cap-content,并调用 setDirection('forward') 或 setDirection('back') 在导航之前。请勿在原生导航拥有这些表面的网页头部或底部时重复网页头部或底部。
查看完整指南: 使用@capgo/capacitor原生导航 和 使用@capgo/capacitor过渡.
安全区域使用Tailwind
在Tailwind CSS中,使用 @capgo/tailwind-capacitor (发布于 tailwind-capacitor npm)。它提供 safe-areas Capacitor友好的Tailwind插件:
bun add -D tailwind-capacitor
在 src/index.css:
@import 'tailwindcss';
@plugin "@capgo/tailwind-capacitor/platform";
@plugin "@capgo/tailwind-capacitor/safe-areas";
使用如下的工具 pt-safe, pb-safe, 和 px-safe 而不是手动添加 env(safe-area-inset-*) 该项目正在积极开发中 — 如果您的 React 设置中缺少某些功能,请 在 GitHub 上打开一个 PR.
修复 iOS 布局问题(视口、安全区域和水平溢出)
如果内容在 iOS 上被裁切、偏移或水平滚动,请尝试 overflow-x: hidden 或调整视口标签通常无法解决问题。按照以下顺序检查这些问题。
确保视口元标签正确应用
在 index.html 添加视口元标签 <head>:
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
在内
创建一个单独的应用程序外壳并在那里应用安全区域填充 — 不是在多个嵌套组件中:
html,
body,
#root {
width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
overflow-x: hidden;
}
* {
box-sizing: border-box;
}
.app-shell {
min-height: 100dvh;
width: 100%;
padding-top: env(safe-area-inset-top);
padding-right: env(safe-area-inset-right);
padding-bottom: env(safe-area-inset-bottom);
padding-left: env(safe-area-inset-left);
}
将所有页面内容包装在 .app-shell. 在头部、模态对话框和布局包装器中重复的安全区域填充通常会使 UI 看起来被裁剪或过大。
使用 @capgo/tailwind-capacitor,您可以用类似于 pt-safe pb-safe px-safe 的工具表达相同的填充。
设置Capacitor iOS contentInset 为 never ,首先
在 capacitor.config.ts中,优先使用原生禁用内边距并让 CSS (或 Native Navigation 的 contentInsetMode: 'css') own the safe area:
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'my-app',
webDir: 'build',
ios: {
contentInset: 'never',
},
};
混合 Capacitor 自动内容内边距与 CSS env(safe-area-inset-*) 使用 padding 是双倍间距的常见原因。
找到真正溢出的元素
通常的罪魁祸首是使用 100vw, Tailwind w-screen, 固定像素宽度, 或一个很大的 min-width.
在 Safari Web Inspector 中运行:
[...document.querySelectorAll('*')]
.filter(el => el.scrollWidth > document.documentElement.clientWidth)
.map(el => ({
el,
tag: el.tagName,
class: el.className,
scrollWidth: el.scrollWidth,
clientWidth: document.documentElement.clientWidth,
}));
使用 Tailwind 替换 w-screen 当可能时, 使用 w-full 许多水平溢出问题来自 100vw / w-screen, 重复的安全区域内边距, 或一个固定宽度的容器 —— 而不是来自视口元标签本身。
结论
Capacitor 提供了基于现有 web 项目构建原生应用的无缝方式,提供了一个简单的方法来共享 code 并保持一致的 UI。
感谢像 Capacitor 这样的技术,使用 React.js web 应用构建移动应用从未如此简单。将您的 web 开发技能提升到下一个水平,创造出令人印象深刻的原生移动应用。开心地编码!
了解如何快速推进您的应用开发过程 立即注册一个免费账户 继续阅读 Building Mobile Apps with Pure React.js 和 __CAPGO_KEEP_0__
Keep going from Building Mobile Apps with Pure React.js and Capacitor
Building Mobile Apps with Pure React.js 和 __CAPGO_KEEP_0__ Building Mobile Apps with Pure React.js and Capacitor 使用 @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-live-activities 为在 Using @capgo/capacitor-live-activities 中的原生能力 for the native capability in Using @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的实现细节,以及 使用capgo/capacitor-native-navigation 为capgo/capacitor-native-navigation的原生能力。