跳至主内容
版本:当前版本

与现有应用集成

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

React Native 非常适合从零开始构建全新的移动应用。同时,它也适用于在现有原生应用中添加单个视图或用户流程。只需几个步骤,你就能添加基于 React Native 的新功能、屏幕、视图等。

具体步骤因目标平台而异。

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

核心概念​

将 React Native 组件集成到 Android 应用程序的关键步骤包括:

  1. 建立正确的目录结构

  2. 安装必要的 NPM 依赖项

  3. 在 Gradle 配置中添加 React Native

  4. 编写首个 React Native 屏幕的 TypeScript 代码

  5. 通过 ReactActivity 将 React Native 集成到 Android 代码中

  6. 运行打包器测试集成效果并查看应用运行情况

使用社区模板​

在遵循本指南时,建议您参考 React Native 社区模板。该模板包含一个精简的 Android 应用,能帮助您理解如何将 React Native 集成到现有 Android 应用中。

准备工作​

请先按照设置开发环境和无框架使用 React Native指南配置 Android 应用的 React Native 开发环境。 本指南同时假设您熟悉 Android 开发基础知识,例如创建 Activity 和编辑 AndroidManifest.xml 文件。

1. 设置目录结构​

为确保流程顺畅,请为集成项目创建新文件夹,并将现有 Android 项目移动到 /android 子目录。

2. 安装 NPM 依赖项​

进入项目根目录后运行以下命令:

shell
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/当前版本-stable/template/package.json

This will copy the package.json file from the Community template to your project.

接着运行以下命令安装 NPM 包:

npm install

安装过程将创建新的 node_modules 文件夹,该文件夹存储了构建项目所需的所有 JavaScript 依赖项。

Add node_modules/ to your .gitignore file (here the Community default one).

3. 添加 React Native 到应用​

配置 Gradle​

React Native 使用 React Native Gradle 插件来配置依赖项和项目设置。

First, let's edit your settings.gradle file by adding those lines (as suggested from the Community template):

groovy
// Configures the React Native Gradle Settings plugin used for autolinking
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
// If using .gradle.kts files:
// extensions.configure<com.facebook.react.ReactSettingsExtension> { autolinkLibrariesFromCommand() }
includeBuild("../node_modules/@react-native/gradle-plugin")

// Include your existing Gradle modules here.
// include(":app")

Then you need to open your top level build.gradle and include this line (as suggested from the Community template):

diff
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:7.3.1")
+ classpath("com.facebook.react:react-native-gradle-plugin")
}
}

This makes sure the React Native Gradle Plugin (RNGP) is available inside your project. Finally, add those lines inside your Applications's build.gradle file (it's a different build.gradle file usually inside your app folder - you can use the Community template file as reference):

diff
apply plugin: "com.android.application"
+apply plugin: "com.facebook.react"

repositories {
mavenCentral()
}

dependencies {
// Other dependencies here
+ // Note: we intentionally don't specify the version number here as RNGP will take care of it.
+ // If you don't use the RNGP, you'll have to specify version manually.
+ implementation("com.facebook.react:react-android")
+ implementation("com.facebook.react:hermes-android")
}

+react {
+ // Needed to enable Autolinking - https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
+ autolinkLibrariesWithApp()
+}

Finally, open your application gradle.properties files and add the following line (here the Community template file as reference):

diff
+reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
+newArchEnabled=true
+hermesEnabled=true

配置清单文件​

首先确保 AndroidManifest.xml 中包含网络权限:

diff
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

+ <uses-permission android:name="android.permission.INTERNET" />

<application
android:name=".MainApplication">
</application>
</manifest>

接着在调试版 AndroidManifest.xml 中启用明文传输:

diff
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
+ android:usesCleartextTraffic="true"
+ tools:targetApi="28"
/>
</manifest>

As usual, here the AndroidManifest.xml file from the Community template to use as a reference: main and debug.

这是因为你的应用需要通过 HTTP 协议与本地打包器 Metro 进行通信。

请确保仅在调试清单中添加此项配置。

4. 编写 TypeScript 代码​

现在我们将实际修改原生 Android 应用来集成 React Native。

我们要编写的第一段代码是将要集成到应用中的新屏幕的 React Native 实际代码。

创建 index.js 文件​

首先在 React Native 项目的根目录创建一个空的 index.js 文件。

index.js 是 React Native 应用的入口文件且必须存在。它可以是一个import其他 React Native 组件或应用文件的小文件,也可以包含所需全部代码。

Our index.js should look as follows (here the Community template file as reference):

js
import {AppRegistry} from 'react-native';
import App from './App';

AppRegistry.registerComponent('HelloWorld', () => App);

创建 App.tsx 文件​

Let's create an App.tsx file. This is a TypeScript file that can have JSX expressions. It contains the root React Native component that we will integrate into our Android application (link):

tsx
import React from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';

import {
Colors,
DebugInstructions,
Header,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

function App(): React.JSX.Element {
const isDarkMode = useColorScheme() === 'dark';

const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};

return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode
? Colors.black
: Colors.white,
padding: 24,
}}>
<Text style={styles.title}>Step One</Text>
<Text>
Edit <Text style={styles.bold}>App.tsx</Text> to
change this screen and see your edits.
</Text>
<Text style={styles.title}>See your changes</Text>
<ReloadInstructions />
<Text style={styles.title}>Debug</Text>
<DebugInstructions />
</View>
</ScrollView>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
title: {
fontSize: 24,
fontWeight: '600',
},
bold: {
fontWeight: '700',
},
});

export default App;

Here is the Community template file as reference.

5. 与 Android 代码集成​

现在我们需要添加一些原生代码来启动 React Native 运行时并渲染 React 组件。

更新 Application 类​

首先更新 Application 类以正确初始化 React Native:

diff
package <your-package-here>;

import android.app.Application;
+import com.facebook.react.PackageList;
+import com.facebook.react.ReactApplication;
+import com.facebook.react.ReactHost;
+import com.facebook.react.ReactNativeHost;
+import com.facebook.react.ReactPackage;
+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
+import com.facebook.react.defaults.DefaultReactHost;
+import com.facebook.react.defaults.DefaultReactNativeHost;
+import com.facebook.soloader.SoLoader;
+import com.facebook.react.soloader.OpenSourceMergedSoMapping
+import java.util.List;

-class MainApplication extends Application {
+class MainApplication extends Application implements ReactApplication {
+ @Override
+ public ReactNativeHost getReactNativeHost() {
+ return new DefaultReactNativeHost(this) {
+ @Override
+ protected List<ReactPackage> getPackages() { return new PackageList(this).getPackages(); }
+ @Override
+ protected String getJSMainModuleName() { return "index"; }
+ @Override
+ public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; }
+ @Override
+ protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; }
+ @Override
+ protected Boolean isHermesEnabled() { return BuildConfig.IS_HERMES_ENABLED; }
+ };
+ }

+ @Override
+ public ReactHost getReactHost() {
+ return DefaultReactHost.getDefaultReactHost(getApplicationContext(), getReactNativeHost());
+ }

@Override
public void onCreate() {
super.onCreate();
+ SoLoader.init(this, OpenSourceMergedSoMapping);
+ if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
+ DefaultNewArchitectureEntryPoint.load();
+ }
}
}

As usual, here the MainApplication.kt Community template file as reference.

创建 ReactActivity​

最后需要创建继承 ReactActivity 的新 Activity 来托管 React Native 代码。该 Activity 负责启动 React Native 运行时并渲染 React 组件。

java
// package <your-package-here>;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;

public class MyReactActivity extends ReactActivity {

@Override
protected String getMainComponentName() {
return "HelloWorld";
}

@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new DefaultReactActivityDelegate(this, getMainComponentName(), DefaultNewArchitectureEntryPoint.getFabricEnabled());
}
}

As usual, here the MainActivity.kt Community template file as reference.

创建新 Activity 后,需将其添加到 AndroidManifest.xml 文件中。同时必须将 MyReactActivity 的主题设置为 Theme.AppCompat.Light.NoActionBar(或任何非 ActionBar 主题),否则应用会在 React Native 界面上方渲染操作栏:

diff
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name=".MainApplication">

+ <activity
+ android:name=".MyReactActivity"
+ android:label="@string/app_name"
+ android:theme="@style/Theme.AppCompat.Light.NoActionBar">
+ </activity>
</application>
</manifest>

现在你的 Activity 已准备好运行 JavaScript 代码。

6. 测试集成​

已完成 React Native 与应用程序集成的基本步骤。现在我们将启动 Metro 打包工具,将 TypeScript 应用代码编译成资源包。Metro 的 HTTP 服务器在您的开发环境中通过 localhost 将资源包共享给模拟器或真机,从而实现热重载功能。

首先在项目根目录创建如下内容的 metro.config.js 文件:

js
const {getDefaultConfig} = require('@react-native/metro-config');
module.exports = getDefaultConfig(__dirname);

You can checkout the metro.config.js file from the Community template file as reference.

配置文件就绪后,即可运行打包器。在项目根目录下运行以下命令:

npm start

现在像往常一样构建并运行你的 Android 应用。

当应用进入 React 驱动的界面时,会从开发服务器加载 JavaScript 代码并显示:

在 Android Studio 中创建发布版本​

你也可以使用 Android Studio 创建发布版本!操作过程与原生的 Android 应用发布构建同样便捷。

React Native Gradle 插件会自动将 JS 代码打包到 APK/App Bundle 中。

若不使用 Android Studio,可通过以下命令创建发布版本:

cd android
# For a Release APK
./gradlew :app:assembleRelease
# For a Release AAB
./gradlew :app:bundleRelease

后续步骤​

现在你可继续常规应用开发。参考调试和设备运行文档了解更多 React Native 工作流程。