能否在原生Kotlin Android、Swift iOS项目中接入React Native?附入门指引
在现有原生Android(Kotlin)和iOS(Swift)项目中接入React Native的可行方案与入门步骤
完全可以在现有原生项目中接入React Native,这种混合开发模式能保留你已有的Kotlin/Swift业务代码,同时利用RN快速开发跨平台新功能。下面是具体的入门实现步骤:
Android(Kotlin)接入步骤
1. 初始化RN依赖
- 在原生Android项目根目录创建
package.json文件,内容如下:
{ "name": "MyRNModule", "version": "0.0.1", "private": true, "scripts": { "start": "react-native start", "test": "jest" }, "dependencies": { "react": "18.2.0", "react-native": "0.72.0" }, "devDependencies": { "@babel/core": "^7.20.0", "@babel/preset-env": "^7.20.0", "@babel/runtime": "^7.20.0", "@react-native/eslint-config": "^0.72.0", "@react-native/metro-config": "^0.72.0", "@tsconfig/react-native": "^3.0.0", "@types/react": "^18.0.24", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.2.1", "eslint": "^8.19.0", "jest": "^29.2.1", "metro-react-native-babel-preset": "0.76.5", "prettier": "^2.4.1", "react-test-renderer": "18.2.0", "typescript": "4.8.4" } }
- 确保本地装有Node.js(推荐16+版本),执行
npm install安装依赖。
2. 配置Android项目
- 在项目根目录
settings.gradle中添加RN模块配置:
include ':app', ':react-native' project(':react-native').projectDir = new File(rootProject.projectDir, '../node_modules/react-native/ReactAndroid')
- 在
app/build.gradle的dependencies块中添加RN相关依赖:
implementation project(':react-native') implementation "com.facebook.fresco:fresco:2.6.0" implementation "com.facebook.fresco:animated-gif:2.6.0"
- 同步Gradle,等待依赖下载完成。
3. 创建RN页面并嵌入原生
- 在项目根目录创建
index.js,编写基础RN组件:
import React from 'react'; import { View, Text, StyleSheet, AppRegistry } from 'react-native'; const RNTestPage = () => { return ( <View style={styles.container}> <Text style={styles.text}>这是嵌入的React Native页面</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f5fcff', }, text: { fontSize: 20, textAlign: 'center', margin: 10, }, }); AppRegistry.registerComponent('RNTestPage', () => RNTestPage);
- 创建Kotlin Activity加载RN页面:
import com.facebook.react.ReactInstanceManager import com.facebook.react.ReactPackage import com.facebook.react.common.LifecycleState import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler import com.facebook.react.shell.MainReactPackage import com.facebook.soloader.SoLoader class RNTestActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler { private lateinit var reactInstanceManager: ReactInstanceManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) SoLoader.init(this, false) reactInstanceManager = ReactInstanceManager.builder() .setApplication(application) .setCurrentActivity(this) .setBundleAssetName("index.android.bundle") .setJSMainModulePath("index") .addPackage(MainReactPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build() val reactRootView = ReactRootView(this) reactRootView.startReactApplication(reactInstanceManager, "RNTestPage", null) setContentView(reactRootView) } override fun invokeDefaultOnBackPressed() = super.onBackPressed() override fun onPause() { super.onPause() reactInstanceManager.onHostPause(this) } override fun onResume() { super.onResume() reactInstanceManager.onHostResume(this, this) } override fun onDestroy() { super.onDestroy() reactInstanceManager.onHostDestroy(this) } override fun onBackPressed() { reactInstanceManager.onBackPressed() super.onBackPressed() } }
- 在
AndroidManifest.xml中注册该Activity,并添加网络权限(调试用):
<uses-permission android:name="android.permission.INTERNET" /> <activity android:name=".RNTestActivity" />
4. 运行调试
- 执行
npm start启动RN Metro服务,然后运行Android原生项目,打开RNTestActivity即可看到RN页面。
iOS(Swift)接入步骤
1. 初始化RN依赖
- 和Android步骤一致,在iOS项目根目录创建相同的
package.json,执行npm install安装依赖。
2. 配置iOS项目
- 在
Podfile中添加RN相关依赖:
pod 'React', :path => '../node_modules/react-native/' pod 'React-Core', :path => '../node_modules/react-native/React' pod 'React-DevSupport', :path => '../node_modules/react-native/React' pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text' pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image' pod 'RCTRequired', :path => '../node_modules/react-native/Libraries/RCTRequired' pod 'RCTTypeSafety', :path => '../node_modules/react-native/Libraries/TypeSafety' pod 'FBLazyVector', :path => '../node_modules/react-native/Libraries/FBLazyVector' pod 'FBReactNativeSpec', :path => '../node_modules/react-native/Libraries/FBReactNativeSpec' pod 'CoreModules', :path => '../node_modules/react-native/React/CoreModules' pod 'ReactCommon/turbomodule/core', :path => '../node_modules/react-native/ReactCommon' pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
- 执行
pod install,打开生成的.xcworkspace文件。
3. 创建RN页面并嵌入原生
- 根目录的
index.js内容和Android部分一致。 - 创建Swift ViewController加载RN页面:
import UIKit import React class RNTestViewController: UIViewController, RCTBridgeDelegate { private var bridge: RCTBridge! private var reactRootView: RCTRootView! override func viewDidLoad() { super.viewDidLoad() bridge = RCTBridge(delegate: self, launchOptions: nil) reactRootView = RCTRootView(bridge: bridge, moduleName: "RNTestPage", initialProperties: nil) view = reactRootView } func sourceURL(for bridge: RCTBridge!) -> URL! { // 调试用Metro服务地址,发布时替换为本地bundle文件路径 return URL(string: "http://localhost:8081/index.bundle?platform=ios&dev=true") } }
- 在
Info.plist中添加App Transport Security例外(调试用):
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
4. 运行调试
- 执行
npm start启动Metro服务,运行iOS项目,导航到RNTestViewController即可看到RN页面。
关键注意事项
- 确保Node.js版本与所选RN版本兼容,避免依赖安装失败。
- 发布版本时,需要将RN bundle打包到原生项目中:
- Android:执行
npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/ - iOS:执行
npx react-native bundle --platform ios --dev false --entry-file index.js --bundle-output ios/main.jsbundle --assets-dest ios/,然后在Xcode中配置bundle路径。
- Android:执行
- 原生与RN的通信可通过
NativeModules(RN调用原生)和RCTEventEmitter(原生调用RN)实现,后续可按需扩展。
内容的提问来源于stack exchange,提问作者Fred Shmed
相关产品推荐
相关产品推荐

