美文网首页React native
Android 原生嵌入React-native 开篇

Android 原生嵌入React-native 开篇

作者: cherishyan | 来源:发表于2017-02-17 11:18 被阅读2176次

    开篇主要记录在原有Android项目中嵌入React-native的基本步骤。系统环境为mac,已经安装配置node和npm。

    网上有非常多的导入资料,这里我就不在过多赘述大部分文章都有的内容,基本概括一下,具体描述遇到的问题。

    • npm init
      在已有的Android项目或者新建的Android项目中,打开Terminal,我已经将默认.bash替换成了zsh。
    Paste_Image.png

    这里默认进入项目根目录下,如果直接打开ITerm,也可以直接cd到你的项目根目录下进行操作。

    输入以下命令:

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

    init创建过程中可能会初步设置一些参数:

    Paste_Image.png

    这些参数可以后面在package.json中修改。

    以上命令执行完,工程中应该会出现node_modules包,说明react和react-native安装了。

    • 配置package.json
      在生成的package.json的scripts中加入start,如上图部分,这是npm start入口。
      最好同时加入budle-android:
    Paste_Image.png

    "bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output Widgets/app/src/main/assets/index.android.bundle --sourcemap-output Widgets/app/src/main/assets/index.android.map --assets-dest Widgets/app/src/main/res/"
    可能会出现的问题后面再讲。

    • 在项目根目录新建index.android.js
    'use strict';
    import React, { Component } from 'react';
    import {
      AppRegistry,
      StyleSheet,
      Text,
      View
    } from 'react-native';
    
    class Widgets extends Component {
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
              我是 原生项目嵌入的 ReactNative
            </Text>
            <Text style={styles.instructions}>
              Press Cmd+R to reload,{'\n'}
              Cmd+D or shake for dev menu
            </Text>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
    });
    
    AppRegistry.registerComponent('reactactivity', () => Widgets);
    

    代码只是实例,但是最后一句()=>Widgets需要是你的class名。

    • 配置app下gradle和项目下gradle:
      app中的build.gradle加入react-native的依赖:
    dependencies {
     ...
     compile 'com.facebook.react:react-native:+' // From node_modules.
    }
    
    

    项目gradle加入maven库:

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

    接下来 编译如果没有问题,External Libraries中会出现依赖包:

    Paste_Image.png

    目前我集成的版本是0.41.2.

    • 接着在Android项目中新建一个类,并在setContentView()方法中嵌入ReactRootView:
    public class ReactActivity 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(true)
                    .setInitialLifecycleState(LifecycleState.RESUMED)
                    .build();
            mReactRootView.startReactApplication(mReactInstanceManager, "reactactivity", 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
        public void onBackPressed() {
            if (mReactInstanceManager != null) {
                mReactInstanceManager.onBackPressed();
            } else {
                super.onBackPressed();
            }
        }
    
    

    我们可能需要在自定义的Application中实现ReactApplication的接口:

    Paste_Image.png

    接下来,我们写一个Fragment或者Activity作为入口,点击跳转到ReacActivity中:

    Paste_Image.png

    基本配置已经完成,接下来应该就可以npm start了:

    Paste_Image.png

    如果发现如下问题:

    图片选自网络.png

    bundle-android就用在此处!这是因为bundle没有打包好。找不到编译打包后的js文件。其实就是android studio默认的寻找js文件地址和react-native自己的工具编译所使用的地址不同。
    解决方案是:我们在app/src/main 下建立asserts文件夹,并加入上面在package.json的Script中添加的bundle-android了。

    同时我们注意,真机调试的时候,需要设置一下端口号:

    adb reverse tcp:8081 tcp:8081
    

    如果发现在mac中adb没有作用,检查一下你是否在.bash_profile中是否配置了adb。
    如果使用zsh,也在.bash_profile中配置了adb,还是没用??
    .zshrc中引用一下.bash_profile

    source ~/.bash_profile
    ANDROID_PATH=/Users/xxx/Library/Android/sdk/platform-tools
    export ANDROID_PATH
    

    至此,基本配置完成:

    Paste_Image.png Paste_Image.png

    相关文章

      网友评论

        本文标题:Android 原生嵌入React-native 开篇

        本文链接:https://www.haomeiwen.com/subject/xpykwttx.html