Android 原生到 React Native 移植

1,188 阅读2分钟
原文链接: blog.csdn.net

Android原生到React Native移植

一、前言

近来由于项目需要,要在原生的项目中集成React Native,但由于AndroidiOS都需要使用所以先由iOS去配置,然后再从iOS基础上依赖他去配置,不由得增加了很多工作,但是Android的配置和正常的原生项目移植还是大同小异的,下面就来完成原生到 React 项目移植。
注:楼主使用的win电脑

二、开发环境准备

首先你需要有Android Studio、WebStorm并且已经完成了React Native开发环境的搭建。
此次演示React版本为:"react": "15.3.2","react-native": "0.34.1",

三、项目移植

(1)React 端需要做的工作

1.首先新建一个ReactTest目录作为以后的react开发目录

2.在ReactTest目录下运行npm init命令用于初始化json配置,如下:  
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (react_test)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\test\react_test\package.json:

{
  "name": "react_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) yes

命令执行完成后会在目录下生成一个package.json文件
注意:name必须为全英文小写

3.打开json文件,在script中增加如下代码:
"start": "node node_modules/react-native/local-cli/cli.js start"
同时增加react的相关依赖
"dependencies": {"react": "15.3.2","react-native": "0.34.1"}

4.执行npm install安装依赖模块

5.curl -o .flowconfig  https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

做一下flow配置,到此react的配置已经完成,只需最后增肌一个js显示就ok

(2)Android端需要做的工作

1.将我们的原生项目拷贝到ReactTest下,并将原生项目的文件夹名称变为android

2.使用Android Studio打开ReactTest目录下的android

3.在Android项目中的build.gradle中添加React Native 依赖,如下:
compile 'com.facebook.react:react-native:+'
4.需要在AndroidManifest.xml中加入网络权限,因为在我们开发阶段需要连接到本地服务,网络请求就必不可少了,当我们打包上线如果在本地打离线包,则可删除此权限
<uses -permission android:name="android.permission.INTERNET" />

5.在Android项目中新建一个名字为MainActivity的activity作为进入React的入口,代码如下:
package com.book;

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 "book";
    }
}

在此处的book是作为原生和后续的react连接的依据。

    6.在android 的gradle中添加ReactNative的本地maven目录,如下:
allprojects {
    repositories {
        jcenter()
        maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/node_modules/react-native/android"
        }
    }
}
7.在我们自己的android Application中实现ReactApplication,如下:
public class MainApplication extends Application implements ReactApplication {

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

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
      return mReactNativeHost;
  }
}

注:getUseDeveloperSupport在.041的react-native版本变为public方法

8.  在ReactTest目录下创建index.android.js文件,添加如下代码:
'use strict';

import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class ReactApp extends React.Component {
  render() {
    return (
      <View >
        <Text style={styles.hello}>Hello, World</Text>
      </View>
    )
  }
}
var styles = StyleSheet.create({
  hello: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

AppRegistry.registerComponent('book', () => ReactApp );

至此我们就完成了在Android的原生项目中集成React Native.

四、后续问题

1.使用一个新的项目直接导入还会出现.so库找不见问题,解决方法如下:

    早build.gradle中添加
ndk {
abiFilters "armeabi-v7a", "x86"
}
    方案链接:http://www.jianshu.com/p/67c574236e8f

2.65535问题

    因为此次演示只是在空的新项目中,但是实际情况中还会因为依赖包过多出现65535问题,具体提示如下:
    ![这里写图片描述](http://img.blog.csdn.net/20170226123937840?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjcwODI4Mzc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

    此处暂时使用Google提供的multidex解决,方法如下:

    (1)增加依赖compile 'com.android.support:multidex:1.0.0'
    (2)在defaultConfig设置 multiDexEnabled true
    (3)在自定义的Application中实现
@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
3.Conflict with dependency 'com.google.code.findbugs:jsr305'问题

    在build.gradle中增加配置
configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
4.当build version为23版本,会出现org.apache.http.Header找不见,解决如下:

build增加  useLibrary 'org.apache.http.legacy'

到此已经完成了集成,以及在现有我的项目中出现的问题,还有部分问题未标注出来。

Git地址:github.com/Jiepeixuan/…