ionic-react

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ionic 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

前置要求

  1. Ionic Framework 7 or 8 with
    @ionic/react
    .
  2. React 18 or later.
  3. Node.js and npm installed.
  4. For iOS: Xcode installed.
  5. For Android: Android Studio installed.
  1. 搭配
    @ionic/react
    Ionic Framework 7或8
  2. React 18或更高版本。
  3. 已安装Node.js和npm。
  4. 针对iOS:已安装Xcode。
  5. 针对Android:已安装Android Studio。

Agent Behavior

Agent行为准则

  • Auto-detect before asking. Check the project for
    package.json
    dependencies (
    @ionic/react
    ,
    @ionic/react-router
    ,
    react
    ,
    @capacitor/core
    ), platforms (
    android/
    ,
    ios/
    ), build tools, and TypeScript usage. Only ask the user when something cannot be detected.
  • 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/
    ios/
    )、构建工具和TypeScript使用情况。仅当无法检测到相关信息时才询问用户。
  • 分步引导。一次只引导用户完成一个步骤,切勿一次性提出多个不相关的问题。
  • 适配项目实际情况。检测现有代码风格(TypeScript与JavaScript、状态管理库、路由配置),生成匹配的代码。

Procedures

操作流程

Step 1: Analyze the Project

步骤1:分析项目

Auto-detect the following by reading project files:
  1. Ionic version: Read
    @ionic/react
    version from
    package.json
    .
  2. React version: Read
    react
    version from
    package.json
    .
  3. Capacitor version: Read
    @capacitor/core
    version from
    package.json
    (if present).
  4. TypeScript: Check if
    tsconfig.json
    exists and if
    .tsx
    files are used.
  5. Router: Check if
    @ionic/react-router
    and
    react-router-dom
    are in
    package.json
    .
  6. State management: Check
    package.json
    for
    redux
    ,
    @reduxjs/toolkit
    ,
    zustand
    ,
    jotai
    ,
    @tanstack/react-query
    , or similar.
  7. Platforms: Check which directories exist (
    android/
    ,
    ios/
    ).
  8. Build tool: Check for
    vite.config.ts
    ,
    angular.json
    ,
    webpack.config.js
    , etc.
通过读取项目文件自动检测以下信息:
  1. Ionic版本:读取
    package.json
    中的
    @ionic/react
    版本。
  2. React版本:读取
    package.json
    中的
    react
    版本。
  3. Capacitor版本:读取
    package.json
    中的
    @capacitor/core
    版本(如果存在)。
  4. TypeScript配置:检查是否存在
    tsconfig.json
    以及是否使用
    .tsx
    文件。
  5. 路由配置:检查
    package.json
    中是否包含
    @ionic/react-router
    react-router-dom
  6. 状态管理方案:检查
    package.json
    中是否有
    redux
    @reduxjs/toolkit
    zustand
    jotai
    @tanstack/react-query
    等同类依赖。
  7. 支持平台:检查存在哪些平台目录(
    android/
    ios/
    )。
  8. 构建工具:检查是否存在
    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 config
If 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
setupIonicReact()
before rendering the app. This function initializes the Ionic Framework for React.
Verify that
src/main.tsx
(or
src/index.tsx
) contains:
typescript
import { setupIonicReact } from '@ionic/react';

setupIonicReact();
setupIonicReact()
accepts an optional configuration object for global settings:
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
setupIonicReact()
is missing or called after rendering, Ionic components will not function correctly.
入口文件必须在渲染应用前调用
setupIonicReact()
,该函数用于为React初始化Ionic Framework。
请确认
src/main.tsx
(或
src/index.tsx
)包含以下代码:
typescript
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
});
如果缺失
setupIonicReact()
调用或调用时机晚于渲染逻辑,Ionic组件将无法正常运行。

Step 4: Routing and Navigation

步骤4:路由与导航

Read
references/routing.md
for complete routing patterns including:
  • IonReactRouter
    setup
  • IonRouterOutlet
    page management
  • Tab-based navigation with
    IonTabs
  • Side menu navigation with
    IonMenu
  • Programmatic navigation with
    useIonRouter
  • Route guards and route parameters
Key principles:
  1. Use
    IonReactRouter
    instead of React Router's
    BrowserRouter
    . It is required for Ionic page transitions.
  2. Use
    IonRouterOutlet
    to contain routes. It manages the page stack and transition animations.
  3. Pass
    component
    prop to
    Route
    — do not use
    render
    or
    children
    inside
    IonRouterOutlet
    .
  4. Use
    useIonRouter
    for programmatic navigation — it provides Ionic-aware navigation with transition animations.
阅读
references/routing.md
获取完整的路由模式说明,包括:
  • IonReactRouter
    配置
  • IonRouterOutlet
    页面管理
  • 基于
    IonTabs
    的标签页导航
  • 基于
    IonMenu
    的侧边栏导航
  • 使用
    useIonRouter
    的编程式导航
  • 路由守卫与路由参数
核心原则:
  1. **使用
    IonReactRouter
    **而非React Router的
    BrowserRouter
    ,Ionic页面转场效果依赖该组件。
  2. **使用
    IonRouterOutlet
    **承载路由,它负责管理页面栈和转场动画。
  3. Route
    传递
    component
    属性
    ——不要在
    IonRouterOutlet
    内使用
    render
    children
    属性。
  4. **使用
    useIonRouter
    **实现编程式导航,它提供适配Ionic的导航逻辑与转场动画。

Step 5: Ionic Lifecycle Hooks

步骤5:Ionic生命周期钩子

Read
references/lifecycle.md
for detailed lifecycle hook usage.
Ionic React pages stay mounted in the DOM after navigation. Standard React
useEffect
only fires on initial mount, not on every page visit. Use Ionic lifecycle hooks for per-visit logic:
HookUse for
useIonViewWillEnter
Refresh data before the page becomes visible
useIonViewDidEnter
Start animations or focus inputs after page is visible
useIonViewWillLeave
Pause media, save draft state
useIonViewDidLeave
Cleanup after page is fully hidden
These hooks only work in components that:
  • Are rendered as the
    component
    of a
    Route
    inside
    IonRouterOutlet
    .
  • Render
    IonPage
    as their root element.
阅读
references/lifecycle.md
获取生命周期钩子的详细用法。
Ionic React页面在导航后会保留在DOM中,标准React的
useEffect
仅在首次挂载时触发,不会在每次访问页面时触发。针对每次页面访问的逻辑请使用Ionic生命周期钩子:
Hook适用场景
useIonViewWillEnter
页面可见前刷新数据
useIonViewDidEnter
页面可见后启动动画或聚焦输入框
useIonViewWillLeave
暂停媒体播放、保存草稿状态
useIonViewDidLeave
页面完全隐藏后执行清理操作
这些钩子仅在满足以下条件的组件中生效:
  • 作为
    IonRouterOutlet
    Route
    component
    属性渲染。
  • 根元素为
    IonPage
    组件。

Step 6: React-Specific Ionic Hooks

步骤6:React专属Ionic钩子

Read
references/hooks.md
for all available hooks and usage examples.
Ionic React provides hooks for presenting overlays and controlling navigation without managing state manually:
HookPurpose
useIonAlert
Present alert dialogs
useIonToast
Show toast notifications
useIonActionSheet
Present action sheets
useIonLoading
Show/dismiss loading indicators
useIonModal
Present modals programmatically
useIonPopover
Present popovers programmatically
useIonPicker
Present picker dialogs
useIonRouter
Navigate with Ionic animations
阅读
references/hooks.md
获取所有可用钩子的说明与用法示例。
Ionic React提供了无需手动管理状态即可唤起浮层、控制导航的钩子:
Hook用途
useIonAlert
唤起警告弹窗
useIonToast
展示toast通知
useIonActionSheet
唤起操作菜单
useIonLoading
展示/隐藏加载指示器
useIonModal
编程式唤起模态框
useIonPopover
编程式唤起气泡弹窗
useIonPicker
唤起选择器对话框
useIonRouter
带Ionic动画的导航

Step 7: React-Specific Component Patterns

步骤7:React专属组件模式

Read
references/components.md
for detailed component patterns including:
  • Page structure with
    IonPage
  • Inline overlays (modals, popovers) with
    isOpen
    binding
  • Pull-to-refresh with
    IonRefresher
  • Infinite scroll with
    IonInfiniteScroll
  • Forms with Ionic input components
Key principles:
  1. Every page must render
    IonPage
    as root.
    This is required for transitions and lifecycle hooks.
  2. Use
    onIonInput
    for text inputs
    and
    onIonChange
    for select, toggle, checkbox, and range components.
  3. Access values via
    e.detail.value
    (or
    e.detail.checked
    for toggles/checkboxes).
  4. Use inline overlays with
    isOpen
    for simpler state management, or use overlay hooks (
    useIonModal
    ,
    useIonAlert
    , etc.) for imperative usage.
阅读
references/components.md
获取详细的组件模式说明,包括:
  • 基于
    IonPage
    的页面结构
  • 绑定
    isOpen
    属性的内联浮层(模态框、气泡弹窗)
  • 基于
    IonRefresher
    的下拉刷新
  • 基于
    IonInfiniteScroll
    的无限滚动
  • 搭配Ionic输入组件的表单实现
核心原则:
  1. 每个页面必须以
    IonPage
    作为根元素
    ,转场效果和生命周期钩子都依赖该组件。
  2. 文本输入使用
    onIonInput
    事件
    ,选择器、开关、复选框、滑块组件使用
    onIonChange
    事件。
  3. 通过
    e.detail.value
    获取输入值
    (开关/复选框使用
    e.detail.checked
    )。
  4. 简单状态管理优先使用绑定
    isOpen
    的内联浮层
    ,命令式调用场景可使用浮层钩子(
    useIonModal
    useIonAlert
    等)。

Step 8: State Management

步骤8:状态管理

Read
references/state-management.md
for patterns with React Context, Redux Toolkit, Zustand, and TanStack Query.
Key principles:
  1. Page caching affects state. Since Ionic keeps pages mounted, state persists across navigations. Use
    useIonViewWillEnter
    to refresh stale data.
  2. Place providers outside
    IonReactRouter
    .
    Context providers, Redux
    Provider
    , and
    QueryClientProvider
    should wrap the router so all pages have access.
  3. Do not add a state library unless needed. For simple apps, React Context and
    useState
    /
    useReducer
    are sufficient.
阅读
references/state-management.md
获取React Context、Redux Toolkit、Zustand、TanStack Query的适配模式。
核心原则:
  1. 页面缓存会影响状态。由于Ionic会保留页面挂载状态,状态会在多次导航间持久化,可使用
    useIonViewWillEnter
    刷新过期数据。
  2. 将状态提供者放在
    IonReactRouter
    外层
    。Context提供者、Redux
    Provider
    QueryClientProvider
    应当包裹路由组件,确保所有页面都能访问状态。
  3. 非必要不额外引入状态库。简单应用使用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 ios
For development with live reload:
bash
ionic serve
For 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 --external

Error Handling

错误处理

  • Ionic lifecycle hooks not firing: Verify that the component renders
    IonPage
    as its root element and is the
    component
    of a
    Route
    inside
    IonRouterOutlet
    . Lifecycle hooks do not fire in child components or components rendered via
    render
    /
    children
    props.
  • Page transitions not animating: Ensure
    IonReactRouter
    is used instead of
    BrowserRouter
    . Ensure routes use the
    component
    prop, not
    render
    or
    children
    . Verify
    IonRouterOutlet
    is a direct child of
    IonReactRouter
    or
    IonTabs
    .
  • Stale data after navigating back: Ionic keeps pages mounted in the DOM. Use
    useIonViewWillEnter
    to refresh data on every page visit instead of
    useEffect
    with
    []
    .
  • Tab bar disappears on sub-page: All routes (including detail routes) must be inside the
    IonRouterOutlet
    within
    IonTabs
    . Do not nest a separate
    IonRouterOutlet
    inside a tab page.
  • setupIonicReact
    errors or components not rendering
    : Ensure
    setupIonicReact()
    is called before
    ReactDOM.createRoot()
    or
    ReactDOM.render()
    in the entry file. Ensure all Ionic CSS files are imported (see Ionic CSS imports in
    src/App.tsx
    or
    src/main.tsx
    ).
  • IonBackButton
    not appearing
    :
    IonBackButton
    only renders when there is navigation history. Set the
    defaultHref
    prop to provide a fallback route when the page is accessed directly.
  • Form input values not updating: Use
    onIonInput
    for
    IonInput
    /
    IonTextarea
    (not
    onChange
    ). Use
    onIonChange
    for
    IonSelect
    ,
    IonToggle
    ,
    IonCheckbox
    ,
    IonRange
    . Access values via
    e.detail.value
    .
  • Modal or popover content not styled: Ensure the overlay content is wrapped in
    IonContent
    . For modals, include
    IonHeader
    with
    IonToolbar
    if a toolbar is needed.
  • 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.
  • useIonRouter
    returns undefined
    : The hook must be used inside a component that is a descendant of
    IonReactRouter
    . Verify the component tree includes
    IonReactRouter
    as an ancestor.
  • CSS custom properties not applying: Ensure Ionic CSS files are imported in the correct order in
    src/App.tsx
    or
    src/main.tsx
    . The theme
    variables.css
    file must be imported after the core Ionic 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()
    ReactDOM.render()
    之前,确认所有Ionic CSS文件已正确导入(参考
    src/App.tsx
    src/main.tsx
    中的Ionic CSS导入逻辑)。
  • IonBackButton
    不展示
    IonBackButton
    仅在存在导航历史时渲染,直接访问页面时可设置
    defaultHref
    属性提供 fallback 路由。
  • 表单输入值不更新
    IonInput
    /
    IonTextarea
    使用
    onIonInput
    事件而非
    onChange
    IonSelect
    IonToggle
    IonCheckbox
    IonRange
    使用
    onIonChange
    事件,通过
    e.detail.value
    获取输入值。
  • 模态框/气泡弹窗内容无样式:确认浮层内容包裹在
    IonContent
    中,模态框如果需要顶部栏请添加包含
    IonToolbar
    IonHeader
  • React严格模式下组件重复挂载:开发环境下React 18严格模式会将组件挂载两次,可能导致Ionic事件监听器重复注册,确保清理函数能正确移除监听器。
  • useIonRouter
    返回undefined
    :该钩子必须在
    IonReactRouter
    的后代组件中使用,确认组件树中存在
    IonReactRouter
    作为祖先元素。
  • CSS自定义属性不生效:确认
    src/App.tsx
    src/main.tsx
    中Ionic CSS文件的导入顺序正确,主题
    variables.css
    文件必须在核心Ionic CSS之后导入。

Related Skills

相关技能

  • ionic-app-development
    — General Ionic development covering components, theming, and CLI usage.
  • ionic-app-creation
    — Create a new Ionic app from scratch.
  • capacitor-react
    — Capacitor-specific React patterns for accessing native device features (without Ionic Framework).
  • ionic-app-upgrades
    — Upgrade Ionic Framework to a newer version.
  • capacitor-plugins
    — Install, configure, and use Capacitor plugins from official and community sources.
  • ionic-app-development
    ——通用Ionic开发,涵盖组件、主题、CLI使用。
  • ionic-app-creation
    ——从头创建新的Ionic应用。
  • capacitor-react
    ——适用于Capacitor专属的React模式,用于访问原生设备功能(不包含Ionic Framework)。
  • ionic-app-upgrades
    ——升级Ionic Framework到新版本。
  • capacitor-plugins
    ——安装、配置和使用官方及社区提供的Capacitor插件。