ReactNative集成到原生项目

1、准备

1.1 建立 /ios目录,并拷贝iOS原生项目的全部工程文件到该目录下;

1.2 建立/android目录,并拷贝Android原生项目的全部工程文件到该目录下;

1.3 在根目录下建立package.json文件,并添加以下内容:

{
  "name": "MyReactNativeApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  }
}
复制代码

1.4 根目录下执行

yarn add react-native 或者npm i --save react-nativejava

1.5 安装与当前react-native版本配套的react

能够根据步骤四中输出的警告信息查看,具体版本如:warning "react-native@0.57.6" has unmet peer dependency "react@16.6.1". 或者直接查看react-native的package.json中依赖react的版本package.jsonnode

yarn add react@16.6.1npm i --save react@16.6.1react

1.6 目录

image

2、iOS集成

注意:此处默认本机cocoapods已安装完成,未安装的可先google对应教程安装。参考:CocoaPods安装方法android

2.1 在\ios根目录下,终端执行pod init,生成Podfile文件;

2.2 编辑Podfile文件,可参考以下配置:

# Uncomment the next line to define a global platform for your project
 platform :ios, '9.0'
target 'MyReactNativeApp' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for MyReactNativeApp

  # 'node_modules'目录通常位于根目录中
  # 可是若是你的结构不一样,那你就要根据实际路径修改下面的`:path`
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'CxxBridge', # 若是RN版本 >= 0.47则加入此行
    'DevSupport', # 若是RN版本 >= 0.43,则须要加入此行才能开启开发者菜单
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket', # 调试功能须要此模块
    'RCTAnimation', # FlatList和原生动画功能须要此模块
    # 在这里继续添加你所须要的其余RN模块
    'RCTActionSheet',
    'RCTBlob',
    'RCTGeolocation',
    'RCTImage',
    'RCTSettings',
    'RCTVibration',
    'RCTLinkingIOS',

  ]
  # 若是你的RN版本 >= 0.42.0,则加入下面这行
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  # 若是RN版本 >= 0.45则加入下面三个第三方编译依赖
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'


  target 'MyReactNativeAppTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'MyReactNativeAppUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end
复制代码

2.3 执行pod install

2.4 工程根目录下,建立一个组件index.js

import React, {Component} from 'react';
import {
	AppRegistry,
	StyleSheet,
	View,
	Text,
} from 'react-native';
class index extends Component {
	render() {
		return (
			<View style={styles.container}> <Text style={{fontSize:20}}>我是ReactNative !</Text> </View>
		);
	}
}
const styles = StyleSheet.create({
	container:{
		flex:1,
		backgroundColor:'green',
		justifyContent:'center',
		alignItems:'center'
	}
});

AppRegistry.registerComponent("MyReactNativeApp", () => index);
复制代码

2.5 在原生项目中测试:

在须要跳转的页面(ViewController):ios

#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>


- (void)pushToReactNativeVc {
	NSURL *jsBundleLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsBundleLocation moduleName:@"MyReactNativeApp" initialProperties:nil launchOptions:nil];
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self.navigationController pushViewController:vc animated:YES];
}
复制代码

Tips:若是遇到 以下错误c++

image

打开Build Phases→Link Binary With Libraries点击 + ,而后添加以下的.a静态库git

image

3、Android集成

3.1 配置Gradle

3.1.1 在app 中 build.gradle 文件中添加 React Native 依赖

dependencies {
    implementation 'com.android.support:appcompat-v7:23.0.1'
    ...
    implementation "com.facebook.react:react-native:+" // From node_modules
}
复制代码

若是想要指定特定的 React Native 版本,能够用具体的版本号替换 +,固然前提是你从 npm 里下载的是这个版本。github

3.1.2 在项目的 build.gradle 文件中为 React Native 添加一个 maven 依赖的入口,必须写在 "allprojects" 代码块中:

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        ...
    }
    ...
}
复制代码

确保依赖路径的正确!以避免在 Android Studio 运行 Gradle 同步构建时抛出 “Failed to resolve: com.facebook.react:react-native:0.x.x" 异常。objective-c

3.2 配置权限

3.2.1 在 AndroidManifest.xml 清单文件中声明网络权限:

<uses-permission android:name="android.permission.INTERNET" />
复制代码

3.2.2 若是须要访问 DevSettingsActivity 界面(即开发者菜单),则还须要在 AndroidManifest.xml 中声明:

<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
复制代码

修改abiFilters

ndk {
       abiFilters "armeabi-v7a", "x86"
    }
复制代码

缘由:
react-native生成aar的源码在npm install命令下载生成的 '$项目根目录'\node_modules\react-native\ReactAndroid中,aar中关于对于CPU限制在 '$项目根目录'\node_modules\react-native\ReactAndroid\src\main\jni\Application.mk , 在这个文件中,咱们能够到:npm

APP_BUILD_SCRIPT := Android.mk

APP_ABI := armeabi-v7a x86
APP_PLATFORM := android-16

APP_MK_DIR := $(dir $(lastword $(MAKEFILE_LIST)))

NDK_MODULE_PATH := $(APP_MK_DIR)$(HOST_DIRSEP)$(THIRD_PARTY_NDK_DIR)$(HOST_DIRSEP)$(REACT_COMMON_DIR)$(HOST_DIRSEP)$(APP_MK_DIR)first-party

APP_STL := gnustl_shared

# Make sure every shared lib includes a .note.gnu.build-id header
APP_CFLAGS := -Wall -Werror
APP_CPPFLAGS := -std=c++1y
APP_LDFLAGS := -Wl,--build-id

NDK_TOOLCHAIN_VERSION := 4.9
复制代码

说明了CPU的类型限定在了armeabi-v7ax86

3.3 加载ReactNative视图

方式1、继承ReactActivity

  • App内须要使用react-native的页面继承ReactActivity
import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */
    @Override
    protected String getMainComponentName() {
        return "MyReactNativeApp";
    }
}
复制代码
  • Application中实现ReactApplication的方法,以下:
@Override
    public ReactNativeHost getReactNativeHost() {
        return reactNativeHost;
    }

private final ReactNativeHost reactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
                new MainReactPackage()
        );
    }
    @Override
    protected String getJSMainModuleName(){
        return "index";
    }
};
复制代码

方式2、在布局中加入ReactRootView,经过 ReactInstanceManager加载管理JS

  • 一、配置权限以便开发中的红屏错误能正确显示

    若是你的应用会运行在 Android 6.0(API level 23)或更高版本,请确保你在开发版本中有打开悬浮窗(overlay)权限。你能够在代码中使用Settings.canDrawOverlays(this);来检查。之因此须要这一权限,是由于咱们会把开发中的报错显示在悬浮窗中(仅在开发阶段须要)。在 Android 6.0(API level 23)中用户须要手动赞成受权。具体请求受权的作法是在onCreate()中添加以下代码。其中OVERLAY_PERMISSION_REQ_CODE是用于回传受权结果的字段。

private final int OVERLAY_PERMISSION_REQ_CODE = 1;  // 任写一个值

...

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                   Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    }
}
复制代码

重写onActivityResult()方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                // SYSTEM_ALERT_WINDOW permission not granted
            }
        }
    }
}
复制代码
  • 二、接下来添加一些原生代码来启动 React Native 的运行时环境并让它开始渲染。首先须要在一个Activity中建立一个ReactRootView对象,而后在这个对象之中启动 React Native 应用,并将它设为界面的主视图。

若是你想在安卓 5.0 如下的系统上运行,请用 com.android.support:appcompat 包中的 AppCompatActivity 代替 Activity

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // 注意这里的MyReactNativeApp必须对应“index.js”中的
        // “AppRegistry.registerComponent()”的第一个参数
       mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);
        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }
    
    
    @Override
	public void onBackPressed() {
	    if (mReactInstanceManager != null) {
	        mReactInstanceManager.onBackPressed();
	    } else {
	        super.onBackPressed();
	    }
	}
}
复制代码
  • 三、生命周期方法
@Override
protected void onPause() {
    super.onPause();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostPause(this);
    }
}

@Override
protected void onResume() {
    super.onResume();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostResume(this, this);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostDestroy(this);
    }
    if (mReactRootView != null) {
        mReactRootView.unmountReactApplication();
    }
}
复制代码
  • 四、弹出RN的开发者菜单
@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
复制代码

3.4 Android相关报错处理

  • 一、so库冲突
    image

处理:在app下的build.gride中添加以下设置

packagingOptions {
        pickFirst 'lib/x86/libgnustl_shared.so'
        pickFirst 'lib/armeabi-v7a/libgnustl_shared.so'
    }

复制代码
相关文章
相关标签/搜索