跳到主要内容
新架构实战课 实操 + 基建 + 原理全维度包揽,抢先掌握 React Native 新架构精髓 立即查看 >Version: Next

集成到现有原生应用

如果你正准备从头开始制作一个新的应用,那么 React Native 会是个非常好的选择。但如果你只想给现有的原生应用中添加一两个视图或是业务流程,React Native 也同样不在话下。只需简单几步,你就可以给原有应用加上新的基于 React Native 的特性、画面和视图等。

具体的步骤根据你所开发的目标平台不同而不同。

译注:本文档可能更新不够及时,不能保证适用于最新版本,欢迎了解的朋友使用页面底部的编辑链接帮忙改进此文档。一个实用的建议是可以使用npx react-native init NewProject创建一个最新版本的纯 RN 项目,去参考其 Podfile 或是 gradle 等的配置,以它们为准。

核心概念

把 React Native 组件集成到 Android 应用中有如下几个主要步骤:

  1. 配置好项目结构。
  2. 安装必要的 JavaScript 依赖。
  3. 在 Gradle 中配置 React Native 依赖。
  4. 创建 ts 文件,编写 React Native 组件的 ts 代码。
  5. 使用 ReactActivity 来把 React Native 集成到你的 Android 项目代码中。
  6. 运行 Metro 服务,验证集成结果。

使用社区模板

在跟随本指南时,我们建议你使用 React Native Community Template 作为参考。模板包含一个 精简的 Android app 并且可以帮助你理解如何将 React Native 集成到现有的 Android 应用中。

开发环境准备

首先按照开发环境搭建教程来安装 React Native 在 Android 平台上所需的一切依赖软件。

1. 配置项目目录结构

首先创建一个空目录用于存放 React Native 项目,然后在其中创建一个/android子目录,把你现有的 Android 项目拷贝到/android子目录中。

2. 安装 JavaScript 依赖包

在根目录下运行以下命令:

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

这将把 React Native 社区模板 中的 package.json 文件复制到你的项目中。

接下来我们使用 yarn 或 npm(两者都是 node 的包管理器)来安装必要的模块。请打开一个终端/命令提示行,进入到项目目录中(即包含有 package.json 文件的目录),然后运行下列命令来安装:

shell
npm install

所有 JavaScript 依赖模块都会被安装到项目根目录下的node_modules/目录中(这个目录我们原则上不复制、不移动、不修改、不上传,随用随装)。

node_modules/目录记录到.gitignore文件中(即不上传到版本控制系统,只保留在本地)。可以参考 React Native 社区模板 中的.gitignore文件。

把 React Native 添加到你的应用中

配置 Gradle

React Native 使用 React Native Gradle Plugin 来配置您的依赖项和项目设置。

首先,让我们通过添加以下行来编辑您的settings.gradle文件: (请参考 社区模板):

groovy
// 此处配置用于自动链接第三方原生库的 React Native Gradle 插件
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
// 如果使用 .gradle.kts 文件:
// extensions.configure<com.facebook.react.ReactSettingsExtension> { autolinkLibrariesFromCommand() }
includeBuild("../node_modules/@react-native/gradle-plugin")

// 在这里引入你已有的其他 Gradle 模块。
// include(":app")

然后你需要打开顶层的 build.gradle 文件并添加这一行:

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

这将确保 React Native Gradle Plugin 在您的项目中可用。 最后,在 app/build.gradle 文件中添加以下行(注意它的路径不同于上面,这次是 app/build.gradle):

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

repositories {
mavenCentral()
}

dependencies {
// Other dependencies here
+ // 注:我们故意不在这里指定版本号,因为 React Native Gradle Plugin 会自动处理它。
+ // 如果您不使用 React Native Gradle Plugin,则必须手动指定版本。
+ implementation "com.facebook.react:react-android"
+ implementation "com.facebook.react:hermes-android"
}

+react {
+ // 启用自动链接需要添加以下行,参考: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
+ autolinkLibrariesWithApp()
+}

最后,打开应用的 gradle.properties 文件并添加以下行(请参考 社区模板):

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 中启用 允许明文传输 (在src/debug/AndroidManifest.xml 中):

从 Android 9 (API level 28)开始,默认情况下明文传输(http 接口)是禁用的,只能访问 https 接口。这将阻止应用程序连接到Metro bundler。下面的更改允许调试版本中的明文通信。

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>

同样可以参考社区模板的 AndroidManifest.xml 文件:maindebug

如果希望在正式打包后也能继续访问 http 接口,则需要在src/main/AndroidManifest.xml中也添加这一选项。

要了解有关网络安全配置和明文通信策略的更多信息,请参阅此链接

代码集成

现在我们将修改原生 Android 应用程序以集成 React Native。

React Native 组件

我们首先要写的是"High Score"(得分排行榜)的 JavaScript 端的代码。

创建一个index.js文件

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

index.js是 React Native 应用在 Android 上的入口文件。而且它是不可或缺的!它可以是个很简单的文件,简单到可以只包含一行require/import导入语句。

本教程的index.js文件应该如下所示(请参考 社区模板):

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

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

创建一个 App.tsx 文件

下面我们创建一个 App.tsx 文件。这是一个 TypeScript 文件,可以包含 JSX 表达式。它包含了我们将在 Android 应用中集成的根 React Native 组件(请参考 社区模板):

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;

5. Integrating with your Android code

We now need to add some native code in order to start the React Native runtime and tell it to render our React components.

Updating your Application class

First, we need to update your Application class to properly initialize React Native as follows:

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

Creating a ReactActivity

Finally, we need to create a new Activity that will extend ReactActivity and host the React Native code. This activity will be responsible for starting the React Native runtime and rendering the React component.

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

Whenever you create a new Activity, you need to add it to your AndroidManifest.xml file. You also need set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar (or to any non-ActionBar theme) as otherwise your application will render an ActionBar on top of your React Native screen:

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>

Now your activity is ready to run some JavaScript code.

6. Test your integration

You have completed all the basic steps to integrate React Native with your application. Now we will start the Metro bundler to build your TypeScript application code into a bundle. Metro's HTTP server shares the bundle from localhost on your developer environment to a simulator or device. This allows for hot reloading.

First, you need to create a metro.config.js file in the root of your project as follows:

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.

Once you have the config file in place, you can run the bundler. Run the following command in the root directory of your project:

shell
npm start

Now build and run your Android app as normal.

Once you reach your React-powered Activity inside the app, it should load the JavaScript code from the development server and display:

Creating a release build in Android Studio

You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.

The React Native Gradle Plugin will take care of bundling the JS code inside your APK/App Bundle.

If you're not using Android Studio, you can create a release build with:

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

Now what?

At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.