ionic-react
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseIonic React
Ionic React
Develop Ionic Framework apps with React — project structure, IonReactRouter, React-specific components, lifecycle hooks, state management, and best practices.
使用React开发Ionic Framework应用——涵盖项目结构、IonReactRouter、React专属组件、生命周期钩子、状态管理与最佳实践。
Prerequisites
前置要求
- Ionic Framework 7 or 8 with .
@ionic/react - React 18 or later.
- Node.js and npm installed.
- For iOS: Xcode installed.
- For Android: Android Studio installed.
- 搭配的Ionic Framework 7或8。
@ionic/react - React 18或更高版本。
- 已安装Node.js和npm。
- 针对iOS:已安装Xcode。
- 针对Android:已安装Android Studio。
Agent Behavior
Agent行为准则
- Auto-detect before asking. Check the project for dependencies (
package.json,@ionic/react,@ionic/react-router,react), platforms (@capacitor/core,android/), build tools, and TypeScript usage. Only ask the user when something cannot be detected.ios/ - Guide step-by-step. Walk the user through the process one step at a time. Never present multiple unrelated questions at once.
- Adapt to the project. Detect the existing code style (TypeScript vs. JavaScript, state management library, routing setup) and generate code that matches.
- 提问前自动检测。检查项目的依赖(
package.json、@ionic/react、@ionic/react-router、react)、平台(@capacitor/core、android/)、构建工具和TypeScript使用情况。仅当无法检测到相关信息时才询问用户。ios/ - 分步引导。一次只引导用户完成一个步骤,切勿一次性提出多个不相关的问题。
- 适配项目实际情况。检测现有代码风格(TypeScript与JavaScript、状态管理库、路由配置),生成匹配的代码。
Procedures
操作流程
Step 1: Analyze the Project
步骤1:分析项目
Auto-detect the following by reading project files:
- Ionic version: Read version from
@ionic/react.package.json - React version: Read version from
react.package.json - Capacitor version: Read version from
@capacitor/core(if present).package.json - TypeScript: Check if exists and if
tsconfig.jsonfiles are used..tsx - Router: Check if and
@ionic/react-routerare inreact-router-dom.package.json - State management: Check for
package.json,redux,@reduxjs/toolkit,zustand,jotai, or similar.@tanstack/react-query - Platforms: Check which directories exist (,
android/).ios/ - Build tool: Check for ,
vite.config.ts,angular.json, etc.webpack.config.js
通过读取项目文件自动检测以下信息:
- Ionic版本:读取中的
package.json版本。@ionic/react - React版本:读取中的
package.json版本。react - Capacitor版本:读取中的
package.json版本(如果存在)。@capacitor/core - TypeScript配置:检查是否存在以及是否使用
tsconfig.json文件。.tsx - 路由配置:检查中是否包含
package.json和@ionic/react-router。react-router-dom - 状态管理方案:检查中是否有
package.json、redux、@reduxjs/toolkit、zustand、jotai等同类依赖。@tanstack/react-query - 支持平台:检查存在哪些平台目录(、
android/)。ios/ - 构建工具:检查是否存在、
vite.config.ts、angular.json等配置文件。webpack.config.js
Step 2: Project Structure
步骤2:项目结构
A standard Ionic React project follows this structure:
project-root/
├── android/ # Android native project (Capacitor)
├── ios/ # iOS native project (Capacitor)
├── public/
├── src/
│ ├── components/ # Reusable UI components
│ ├── hooks/ # Custom React hooks
│ ├── pages/ # Page components (one per route)
│ ├── services/ # Service modules for API and native calls
│ ├── context/ # React context providers
│ ├── theme/
│ │ └── variables.css # Ionic CSS custom properties
│ ├── App.tsx # Root component with IonReactRouter
│ └── main.tsx # Entry point with setupIonicReact()
├── capacitor.config.ts # Capacitor configuration
├── ionic.config.json # Ionic CLI configuration
├── package.json
├── tsconfig.json
└── vite.config.ts # Or other bundler configIf the project does not follow this structure, adapt all guidance to the project's actual directory layout. Do not restructure the project unless the user explicitly asks.
标准Ionic React项目遵循以下结构:
project-root/
├── android/ # Android native project (Capacitor)
├── ios/ # iOS native project (Capacitor)
├── public/
├── src/
│ ├── components/ # Reusable UI components
│ ├── hooks/ # Custom React hooks
│ ├── pages/ # Page components (one per route)
│ ├── services/ # Service modules for API and native calls
│ ├── context/ # React context providers
│ ├── theme/
│ │ └── variables.css # Ionic CSS custom properties
│ ├── App.tsx # Root component with IonReactRouter
│ └── main.tsx # Entry point with setupIonicReact()
├── capacitor.config.ts # Capacitor configuration
├── ionic.config.json # Ionic CLI configuration
├── package.json
├── tsconfig.json
└── vite.config.ts # Or other bundler config如果项目不遵循该结构,所有指导内容需适配项目实际的目录布局。除非用户明确要求,否则不要重构项目结构。
Step 3: App Initialization
步骤3:应用初始化
The entry point must call before rendering the app. This function initializes the Ionic Framework for React.
setupIonicReact()Verify that (or ) contains:
src/main.tsxsrc/index.tsxtypescript
import { setupIonicReact } from '@ionic/react';
setupIonicReact();setupIonicReact()typescript
setupIonicReact({
mode: 'ios', // Force iOS mode on all platforms ('ios' | 'md')
rippleEffect: false, // Disable Material Design ripple effect
animated: true, // Enable/disable all animations
});If is missing or called after rendering, Ionic components will not function correctly.
setupIonicReact()入口文件必须在渲染应用前调用,该函数用于为React初始化Ionic Framework。
setupIonicReact()请确认(或)包含以下代码:
src/main.tsxsrc/index.tsxtypescript
import { setupIonicReact } from '@ionic/react';
setupIonicReact();setupIonicReact()typescript
setupIonicReact({
mode: 'ios', // Force iOS mode on all platforms ('ios' | 'md')
rippleEffect: false, // Disable Material Design ripple effect
animated: true, // Enable/disable all animations
});如果缺失调用或调用时机晚于渲染逻辑,Ionic组件将无法正常运行。
setupIonicReact()Step 4: Routing and Navigation
步骤4:路由与导航
Read for complete routing patterns including:
references/routing.md- setup
IonReactRouter - page management
IonRouterOutlet - Tab-based navigation with
IonTabs - Side menu navigation with
IonMenu - Programmatic navigation with
useIonRouter - Route guards and route parameters
Key principles:
- Use instead of React Router's
IonReactRouter. It is required for Ionic page transitions.BrowserRouter - Use to contain routes. It manages the page stack and transition animations.
IonRouterOutlet - Pass prop to
component— do not useRouteorrenderinsidechildren.IonRouterOutlet - Use for programmatic navigation — it provides Ionic-aware navigation with transition animations.
useIonRouter
阅读获取完整的路由模式说明,包括:
references/routing.md- 配置
IonReactRouter - 页面管理
IonRouterOutlet - 基于的标签页导航
IonTabs - 基于的侧边栏导航
IonMenu - 使用的编程式导航
useIonRouter - 路由守卫与路由参数
核心原则:
- **使用**而非React Router的
IonReactRouter,Ionic页面转场效果依赖该组件。BrowserRouter - **使用**承载路由,它负责管理页面栈和转场动画。
IonRouterOutlet - 给传递
Route属性——不要在component内使用IonRouterOutlet或render属性。children - **使用**实现编程式导航,它提供适配Ionic的导航逻辑与转场动画。
useIonRouter
Step 5: Ionic Lifecycle Hooks
步骤5:Ionic生命周期钩子
Read for detailed lifecycle hook usage.
references/lifecycle.mdIonic React pages stay mounted in the DOM after navigation. Standard React only fires on initial mount, not on every page visit. Use Ionic lifecycle hooks for per-visit logic:
useEffect| Hook | Use for |
|---|---|
| Refresh data before the page becomes visible |
| Start animations or focus inputs after page is visible |
| Pause media, save draft state |
| Cleanup after page is fully hidden |
These hooks only work in components that:
- Are rendered as the of a
componentinsideRoute.IonRouterOutlet - Render as their root element.
IonPage
阅读获取生命周期钩子的详细用法。
references/lifecycle.mdIonic React页面在导航后会保留在DOM中,标准React的仅在首次挂载时触发,不会在每次访问页面时触发。针对每次页面访问的逻辑请使用Ionic生命周期钩子:
useEffect| Hook | 适用场景 |
|---|---|
| 页面可见前刷新数据 |
| 页面可见后启动动画或聚焦输入框 |
| 暂停媒体播放、保存草稿状态 |
| 页面完全隐藏后执行清理操作 |
这些钩子仅在满足以下条件的组件中生效:
- 作为内
IonRouterOutlet的Route属性渲染。component - 根元素为组件。
IonPage
Step 6: React-Specific Ionic Hooks
步骤6:React专属Ionic钩子
Read for all available hooks and usage examples.
references/hooks.mdIonic React provides hooks for presenting overlays and controlling navigation without managing state manually:
| Hook | Purpose |
|---|---|
| Present alert dialogs |
| Show toast notifications |
| Present action sheets |
| Show/dismiss loading indicators |
| Present modals programmatically |
| Present popovers programmatically |
| Present picker dialogs |
| Navigate with Ionic animations |
阅读获取所有可用钩子的说明与用法示例。
references/hooks.mdIonic React提供了无需手动管理状态即可唤起浮层、控制导航的钩子:
| Hook | 用途 |
|---|---|
| 唤起警告弹窗 |
| 展示toast通知 |
| 唤起操作菜单 |
| 展示/隐藏加载指示器 |
| 编程式唤起模态框 |
| 编程式唤起气泡弹窗 |
| 唤起选择器对话框 |
| 带Ionic动画的导航 |
Step 7: React-Specific Component Patterns
步骤7:React专属组件模式
Read for detailed component patterns including:
references/components.md- Page structure with
IonPage - Inline overlays (modals, popovers) with binding
isOpen - Pull-to-refresh with
IonRefresher - Infinite scroll with
IonInfiniteScroll - Forms with Ionic input components
Key principles:
- Every page must render as root. This is required for transitions and lifecycle hooks.
IonPage - Use for text inputs and
onIonInputfor select, toggle, checkbox, and range components.onIonChange - Access values via (or
e.detail.valuefor toggles/checkboxes).e.detail.checked - Use inline overlays with for simpler state management, or use overlay hooks (
isOpen,useIonModal, etc.) for imperative usage.useIonAlert
阅读获取详细的组件模式说明,包括:
references/components.md- 基于的页面结构
IonPage - 绑定属性的内联浮层(模态框、气泡弹窗)
isOpen - 基于的下拉刷新
IonRefresher - 基于的无限滚动
IonInfiniteScroll - 搭配Ionic输入组件的表单实现
核心原则:
- 每个页面必须以作为根元素,转场效果和生命周期钩子都依赖该组件。
IonPage - 文本输入使用事件,选择器、开关、复选框、滑块组件使用
onIonInput事件。onIonChange - 通过获取输入值(开关/复选框使用
e.detail.value)。e.detail.checked - 简单状态管理优先使用绑定的内联浮层,命令式调用场景可使用浮层钩子(
isOpen、useIonModal等)。useIonAlert
Step 8: State Management
步骤8:状态管理
Read for patterns with React Context, Redux Toolkit, Zustand, and TanStack Query.
references/state-management.mdKey principles:
- Page caching affects state. Since Ionic keeps pages mounted, state persists across navigations. Use to refresh stale data.
useIonViewWillEnter - Place providers outside . Context providers, Redux
IonReactRouter, andProvidershould wrap the router so all pages have access.QueryClientProvider - Do not add a state library unless needed. For simple apps, React Context and /
useStateare sufficient.useReducer
阅读获取React Context、Redux Toolkit、Zustand、TanStack Query的适配模式。
references/state-management.md核心原则:
- 页面缓存会影响状态。由于Ionic会保留页面挂载状态,状态会在多次导航间持久化,可使用刷新过期数据。
useIonViewWillEnter - 将状态提供者放在外层。Context提供者、Redux
IonReactRouter、Provider应当包裹路由组件,确保所有页面都能访问状态。QueryClientProvider - 非必要不额外引入状态库。简单应用使用React Context和/
useState即可满足需求。useReducer
Step 9: Build and Run
步骤9:构建与运行
After implementing changes:
bash
npm run build
npx cap sync
npx cap run android
npx cap run iosFor development with live reload:
bash
ionic serveFor native development with live reload:
bash
ionic cap run android --livereload --external
ionic cap run ios --livereload --external完成代码变更后执行以下命令:
bash
npm run build
npx cap sync
npx cap run android
npx cap run ios带热重载的开发调试:
bash
ionic serve带热重载的原生端开发调试:
bash
ionic cap run android --livereload --external
ionic cap run ios --livereload --externalError Handling
错误处理
- Ionic lifecycle hooks not firing: Verify that the component renders as its root element and is the
IonPageof acomponentinsideRoute. Lifecycle hooks do not fire in child components or components rendered viaIonRouterOutlet/renderprops.children - Page transitions not animating: Ensure is used instead of
IonReactRouter. Ensure routes use theBrowserRouterprop, notcomponentorrender. Verifychildrenis a direct child ofIonRouterOutletorIonReactRouter.IonTabs - Stale data after navigating back: Ionic keeps pages mounted in the DOM. Use to refresh data on every page visit instead of
useIonViewWillEnterwithuseEffect.[] - Tab bar disappears on sub-page: All routes (including detail routes) must be inside the within
IonRouterOutlet. Do not nest a separateIonTabsinside a tab page.IonRouterOutlet - errors or components not rendering: Ensure
setupIonicReactis called beforesetupIonicReact()orReactDOM.createRoot()in the entry file. Ensure all Ionic CSS files are imported (see Ionic CSS imports inReactDOM.render()orsrc/App.tsx).src/main.tsx - not appearing:
IonBackButtononly renders when there is navigation history. Set theIonBackButtonprop to provide a fallback route when the page is accessed directly.defaultHref - Form input values not updating: Use for
onIonInput/IonInput(notIonTextarea). UseonChangeforonIonChange,IonSelect,IonToggle,IonCheckbox. Access values viaIonRange.e.detail.value - Modal or popover content not styled: Ensure the overlay content is wrapped in . For modals, include
IonContentwithIonHeaderif a toolbar is needed.IonToolbar - React strict mode double-mounting: In development, React 18 strict mode mounts components twice. This can cause duplicate Ionic event listeners. Ensure cleanup functions properly remove listeners.
- returns undefined: The hook must be used inside a component that is a descendant of
useIonRouter. Verify the component tree includesIonReactRouteras an ancestor.IonReactRouter - CSS custom properties not applying: Ensure Ionic CSS files are imported in the correct order in or
src/App.tsx. The themesrc/main.tsxfile must be imported after the core Ionic CSS.variables.css
- Ionic生命周期钩子不触发:确认组件根元素为,且是
IonPage内IonRouterOutlet的Route属性对应的组件。子组件或通过component/render属性渲染的组件不会触发生命周期钩子。children - 页面转场无动画:确保使用的是而非
IonReactRouter,确认路由使用BrowserRouter属性而非component/render,确认children是IonRouterOutlet或IonReactRouter的直接子元素。IonTabs - 返回页面后数据过期:Ionic会将页面保留在DOM中,使用而非空依赖的
useIonViewWillEnter在每次页面访问时刷新数据。useEffect - 子页面标签栏消失:所有路由(包括详情页路由)都必须放在内部的
IonTabs中,不要在标签页内部嵌套独立的IonRouterOutlet。IonRouterOutlet - 报错或组件不渲染:确认入口文件中
setupIonicReact调用在setupIonicReact()或ReactDOM.createRoot()之前,确认所有Ionic CSS文件已正确导入(参考ReactDOM.render()或src/App.tsx中的Ionic CSS导入逻辑)。src/main.tsx - 不展示:
IonBackButton仅在存在导航历史时渲染,直接访问页面时可设置IonBackButton属性提供 fallback 路由。defaultHref - 表单输入值不更新:/
IonInput使用IonTextarea事件而非onIonInput,onChange、IonSelect、IonToggle、IonCheckbox使用IonRange事件,通过onIonChange获取输入值。e.detail.value - 模态框/气泡弹窗内容无样式:确认浮层内容包裹在中,模态框如果需要顶部栏请添加包含
IonContent的IonToolbar。IonHeader - React严格模式下组件重复挂载:开发环境下React 18严格模式会将组件挂载两次,可能导致Ionic事件监听器重复注册,确保清理函数能正确移除监听器。
- 返回undefined:该钩子必须在
useIonRouter的后代组件中使用,确认组件树中存在IonReactRouter作为祖先元素。IonReactRouter - CSS自定义属性不生效:确认或
src/App.tsx中Ionic CSS文件的导入顺序正确,主题src/main.tsx文件必须在核心Ionic CSS之后导入。variables.css
Related Skills
相关技能
- — General Ionic development covering components, theming, and CLI usage.
ionic-app-development - — Create a new Ionic app from scratch.
ionic-app-creation - — Capacitor-specific React patterns for accessing native device features (without Ionic Framework).
capacitor-react - — Upgrade Ionic Framework to a newer version.
ionic-app-upgrades - — Install, configure, and use Capacitor plugins from official and community sources.
capacitor-plugins
- ——通用Ionic开发,涵盖组件、主题、CLI使用。
ionic-app-development - ——从头创建新的Ionic应用。
ionic-app-creation - ——适用于Capacitor专属的React模式,用于访问原生设备功能(不包含Ionic Framework)。
capacitor-react - ——升级Ionic Framework到新版本。
ionic-app-upgrades - ——安装、配置和使用官方及社区提供的Capacitor插件。
capacitor-plugins