原生接入React-Native实战之配置篇

最近工作上的项目要接入react-native技术,因此需要把原生项目接入到rn的配置环境中,整个过程遇到了不少坑,rn以后会是个趋势,也许慢慢会有越来越多的人需要将现有项目接入rn,估计在配置的时候都会遇到一些坑,这篇文章记录下整个配置的过程,既为提自己做个记录,也希望能帮到有同样项目需求的人。

搭建开发环境

开发环境的搭建 这部分只要跟着官方文档里就行,一般都会比较顺利。

完成rn环境配置

进入项目跟目录,使用命令行顺序执行一下三个命令

npm init
npm install –save react react-native
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

在运行过程中我发现自己电脑没有curl这个指令,直接到这个地址 选择你需要的版本下载下来就行

完成上面命令之后你会发现当前目录下多了一个node-mudules文件夹还有一个package.json文件,在package.json文件的scripts部分增加

"start": "node node_modules/react-native/local-cli/cli.js start"


在工程根目录生成新建index.android.js文件,并拷贝如下代码进入,它将作为原生启动的rn代码

'use strict';

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

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

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

原生项目配置

在app的build.gradle增加配置

dependencies {
     ...
     compile "com.facebook.react:react-native:+" // From node_modules.
 }

在整个工程的build.gradle里增加react-native仓库配置

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

上面的$rootDir代表你工程根目录, 有些工程根目录和node_modules的位置关系跟上面写的不一样,执行根据位置关系修改
保证你的项目有访问网络的权限

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

添加原生代码

按照官方文档新建一个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")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setinitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager,"HelloWorld",null);

        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackpressed() {
        super.onBackpressed();
    }

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

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

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

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

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

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy();
        }
    }

    @Override
     public void onBackpressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackpressed();
        } else {
            super.onBackpressed();
        }
    }
}

并配置对应Androidmainfiest

<activity  android:name=".ui.activity.MyReactActivity" android:screenorientation="portrait" />

这个时候基本已经按照官方文档提供的说明完成了配置,然后一点gradle运行,发现报了版本问题,原来项目的最低版本不能满足rn的要求

但上面也给出了解决方案,给uses-sdk增加相应overrideLibrary说明

<uses-sdk  tools:overrideLibrary="com.facebook.react" android:minSdkVersion="14" android:targetSdkVersion="21" />

然后继续打算运行又报错了

这是因为react-native的res使用到了23sdk的资源,因此编译的sdk要求是23,因此修改sdk版本

compileSdkVersion 23
buildToolsversion '23.0.3'

当我们修改了编译的sdk,可能会导致以前的一些sdk调用方法不存在或者不兼容之类的,这个问题根据各自项目自己去修改,比如我的项目就遇到Notification的setLatestEventInfo不存在,修改相应的sdk 23对应的方法,还有一个问题是androidhttpclient这个类在android 23已经被废弃,针对这个问题,在build.gradle增加

android { useLibrary 'org.apache.http.legacy' }

同样的useLibrary这个gradle语句对gradle版本也有要求,我们项目本身的gradle1.2.3,这句配置需要升级到最新版本2.0.0,到整个工程的build.gradle修改gradle版本

dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

修改完运行gradle提示这个问题

同样根据提示修改,在gradle.properties增加

android.useDeprecatedndk=true

同时提示要将gradle版本至少支持2.14.1同样去修改gradle-wrapper.properites里面的gradle地址

distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

最后再来运行下,发现multiDex问题,估计是引入rn的一些方法导致方法数超了吧,这个就好解决

在build.gradle配置

multiDexEnabled true

然后在application增加

@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

这次终于编译通过了。

代码可以部署到设备上,然后在命令行输入npm start,然后启动调用自己的MyReactActivity,大功告成。

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...