React Native 专题React Native开发React Native编程

Android集成ReactNative(0.61.5)

2020-01-07  本文已影响0人  飞奔在路上

前言

为了把 React Native 集成到 Android 原生项目中,遇到不少问题参考了网上很多文章,但是都很旧了,而 React Native 已经升级到了 0.61.5 版本了,在Android中引入了facebook自己研发的JS引擎Hermas更多内容可以点这里,不过因为Apple的某某原因,目前还未使用该引擎,下面的内容也是基于这个版本实践的。
如果对react-native还不了解的同学,可以参考react native中文网

步骤一

先创建一个原生的Android项目(略过...),然后再该项目的根目录中执行

yarn init

根据提示一步步回车,然后会发现根目录中多出来一个package.json文件.
接着执行

yarn add react react-native

然后在package.json中添加如下代码

"scripts": {
    "start": "yarn react-native start",
  },

这样我们的react-native项目就初始化完毕了

步骤二

在根目录下创建一个index.js文件,作为我们rn页面的入口文件

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>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    hello: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
});

AppRegistry.registerComponent('MyReactNativeApp', () => HelloWorld);
步骤三

修改android项目中app目录下的build.gradle文件

project.ext.react = [
        entryFile   : "index.js",//rn项目的入口文件名称
        enableHermes: true  // clean and rebuild if changing
]
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
...
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.android.support:appcompat-v7:27.1.1'
...
步骤四
   maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/node_modules/react-native/android"
        }
        maven {
            url("$rootDir/node_modules/jsc-android/dist")
        }
步骤五
package com.example.mixapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import androidx.annotation.Nullable;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

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

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);

        setContentView(mReactRootView);

    }


    @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();
        }
    }

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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}

步骤六
...
<uses-permission android:name="android.permission.INTERNET" />
...
<application
...
//调出react native的开发者菜单,模拟器中快捷键command+m
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
<activity
      android:name=".MyReactActivity"
      android:label="@string/app_name"
      android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
...
</application>
步骤七
SoLoader.init(this, false);
startActivity(new Intent(this, MyReactActivity.class));
最后一步
react-native bundle --platform android --entry-file index.js --bundle-output app/src/main/assets/index.android.bundle --dev false
yarn start

现在可以点击跳转试试啦

上一篇下一篇

猜你喜欢

热点阅读