有哪些場景是需要混合開發(fā)呢驳糯?
- react-native 原生android的UI的支持
- react-native 的一些交互邏輯需要java處理(比如APP跳轉(zhuǎn)微信小程序)
根據(jù) 單一職責(zé)的原則 腿宰,文章分為三篇梅掠,此篇為react-native 與 java 混合開發(fā) 1/3 框架搭建
關(guān)鍵
關(guān)鍵是js與java的通信
搭建步驟
一. 新建一個(gè)react-native項(xiàng)目和android項(xiàng)目居暖。
- 新建一個(gè)react-native 項(xiàng)目
- 在新建的react-native 項(xiàng)目的根目錄建立新的文件夾android
- 在android目錄下用android studio 建立新的android項(xiàng)目
二. 將新建的兩個(gè)項(xiàng)目聯(lián)系起來
1.在Android Studio中左面菜單欄中選擇Android(默認(rèn)也是這個(gè))究驴,
2.在build.gradle(Project: xxx)中的修改allprojects如下:
allprojects {
repositories {
google()
jcenter()
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
}
3.在build.gradle(Module: app)中的dependencies添加
implementation "com.facebook.react:react-native:+"
三.使用原生調(diào)用我們的JS組件
1.在react-native 的根目錄下新建index.js文件苍蔬,做為的react-native界面的入口文件. 下面代碼中的HelloWorld組件是一個(gè)事例惰蜜,大家自行更換。
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('MyReactNativeApp', () => HelloWorld);
上面代碼的 MyReactNativeApp 是react-native告訴原生android的名稱
2.在原生中新建一個(gè)Activity渲染react-native組件.
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
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();
mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
3.在AndroidManifest.xml中添加activity的聲明
<activity
android:name=".MyReactActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
四.配置權(quán)限
1.在manifests文件夾下的AndroidManifest.xml下添加權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />