A, preparation,
1.1 create/ios
And copy all the project files of the iOS native project to this directory;
1.2 create/android
Directory, and copy all the project files of Android native project to this directory;
1.3 Creating a Vm in the Root directorypackage.json
File and add the following:
{
"name": "MyReactNativeApp"."version": "0.0.1"."private": true."scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"}}Copy the code
1.4 Run the command in the root directory
Yarn add react-native or NPM I –save react-native
1.5 Installation and Currentreact-native
Version matchingreact
You can view the warning information displayed in Step 4. For example, warning “[email protected]” has unmet peer dependency “[email protected]”. Package. json is a react-native version of package.json
Yarn add [email protected] or NPM I –save [email protected]
1.6 directory
Ii. IOS integration
Note: By default, cocoapods has been installed. If not, you can install cocoapods by Google tutorial. Refer to CocoaPods installation method
2.1 in\ios
In the root directory, the terminal executespod init
To generate thePodfile
File;
2.2 the editorPodfile
For details, see the following:
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'MyReactNativeApp' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for MyReactNativeApp
The # 'node_modules' directory is normally in the root directory
# But if your structure is different, then you need to change the following ':path' according to the actual path
pod 'React', :path => '.. /node_modules/react-native', :subspecs => [
'Core'.'CxxBridge'.If RN >= 0.47 join this line
'DevSupport'.# If RN >= 0.43, you need to join this line to open the developer menu
'RCTText'.'RCTNetwork'.'RCTWebSocket'.This module is required for debugging functions
'RCTAnimation'.# FlatList and native animation functions require this module
Continue to add any additional RN modules you need here
'RCTActionSheet'.'RCTBlob'.'RCTGeolocation'.'RCTImage'.'RCTSettings'.'RCTVibration'.'RCTLinkingIOS',]# If your RN version >= 0.42.0, add the following line
pod 'yoga', :path => '.. /node_modules/react-native/ReactCommon/yoga'
Add the following three third-party build dependencies if the RN version >= 0.45
pod 'DoubleConversion', :podspec => '.. /node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '.. /node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '.. /node_modules/react-native/third-party-podspecs/Folly.podspec'
target 'MyReactNativeAppTests' do
inherit! :search_paths
# Pods for testing
end
target 'MyReactNativeAppUITests' do
inherit! :search_paths
# Pods for testing
end
end
Copy the code
2.3 performpod install
2.4 Create a component in the project root directoryindex.js
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
} from 'react-native';
class index extends Component {
render() {
return (
<View style={styles.container}>
<Text style={{fontSize:20}}>I am ReactNative!</Text>
</View>); }}const styles = StyleSheet.create({
container: {flex:1.backgroundColor:'green'.justifyContent:'center'.alignItems:'center'}}); AppRegistry.registerComponent("MyReactNativeApp", () => index);
Copy the code
2.5 Testing in native projects:
On the page to jump to (ViewController) :
#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>
- (void)pushToReactNativeVc {
NSURL *jsBundleLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsBundleLocation moduleName:@"MyReactNativeApp" initialProperties:nil launchOptions:nil];
UIViewController *vc = [[UIViewController alloc] init];
vc.view = rootView;
[self.navigationController pushViewController:vc animated:YES];
}
Copy the code
Tips: If you encounter the following error
Build Phases→Link Binary With Libraries click + and add the following
Android integration
3.1 configuration Gradle
3.1.1 Add the React Native dependency to the build.gradle file in app
dependencies {
implementation 'com. Android. Support: appcompat - v7:23.0.1'. implementation"com.facebook.react:react-native:+" // From node_modules
}
Copy the code
If you want to specify a specific React Native version, you can use the specific version number instead of +, provided you download it from NPM.
3.1.2 Add a Maven dependent entry to React Native in the build.gradle file, which must be written in the “allProjects” code block:
allprojects {
repositories {
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/.. /node_modules/react-native/android"}... }... }Copy the code
Make sure the dependency path is correct! To avoid “Failed to resolve: com.facebook.react:react-native:0.x.x” exception when running Gradle synchronous build in Android Studio.
3.2 Configuring Rights
3.2.1 Declare network permissions in androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Copy the code
3.2.2 If you want to access the DevSettingsActivity interface (i.e. the developer menu), you also need to declare it in androidmanifest.xml:
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
Copy the code
Modify abiFilters
ndk {
abiFilters "armeabi-v7a"."x86"
}
Copy the code
The reason: NPM install: $project root directory \node_modules\react-native\ReactAndroid Aar limits CPU usage to ‘$project root ‘\node_modules\react-native\ReactAndroid\ SRC \main\jni\ application. mk. In this file, we can go to:
APP_BUILD_SCRIPT := Android.mk APP_ABI := armeabi-v7a x86 APP_PLATFORM := android-16 APP_MK_DIR := $(dir $(lastword $(MAKEFILE_LIST))) NDK_MODULE_PATH := $(APP_MK_DIR)$(HOST_DIRSEP)$(THIRD_PARTY_NDK_DIR)$(HOST_DIRSEP)$(REACT_COMMON_DIR)$(HOST_DIRSEP)$(APP_MK_DIR)first-party APP_STL := gnustl_shared# Make sure every shared lib includes a .note.gnu.build-id headerAPP_CFLAGS := -wall-werror APP_CPPFLAGS := -std=c++1y APP_LDFLAGS := -wl,--build-id NDK_TOOLCHAIN_VERSION := 4.9Copy the code
The CPU type is limited to Armeabi-V7A and x86
3.3 Loading the ReactNative View
Method 1: Inherit ReactActivity
- React-native page inheritance is required within the App
ReactActivity
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(a) {
return "MyReactNativeApp"; }}Copy the code
Application
In the implementationReactApplication
The method is as follows:
@Override
public ReactNativeHost getReactNativeHost(a) {
return reactNativeHost;
}
private final ReactNativeHost reactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport(a) {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages(a) {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
@Override
protected String getJSMainModuleName(a){
return "index"; }};Copy the code
Method 2. Add ReactRootView to the layout and load the management JS through ReactInstanceManager
-
1. Configure permissions so that red screen errors in development can be correctly displayed
If your app will run on Android 6.0 (API Level 23) or higher, make sure you have permission to open overlay in the development version. You can use settings. canDrawOverlays(this) in your code; To check. This permission is required because we display development errors in a hover window (only needed during development). In Android 6.0 (API Level 23) users need to manually agree to authorization. To request authorization, add the following code to onCreate(). OVERLAY_PERMISSION_REQ_CODE is the field used to return the authorization result.
private final int OVERLAY_PERMISSION_REQ_CODE = 1; // Write any value.if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(! Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:"+ getPackageName())); startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); }}Copy the code
Override the onActivityResult() method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(! Settings.canDrawOverlays(this)) {
// SYSTEM_ALERT_WINDOW permission not granted}}}}Copy the code
- 2. Next add some Native code to launch the React Native runtime environment and get it rendering. You need to create a ReactRootView object in an Activity, then launch the React Native application within that object and set it as the main view of the interface.
If you want to run on android 5.0 system under, please use the android. Support: appcompat AppCompatActivity Activity instead of package.
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();
// Note that MyReactNativeApp must correspond to "index.js"
. / / "AppRegistry registerComponent ()" the first parameter
mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp".null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed(a) {
super.onBackPressed();
}
@Override
public void onBackPressed(a) {
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed(); }}}Copy the code
- 3. Lifecycle approach
@Override
protected void onPause(a) {
super.onPause();
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onHostPause(this); }}@Override
protected void onResume(a) {
super.onResume();
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onHostResume(this.this); }}@Override
protected void onDestroy(a) {
super.onDestroy();
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onHostDestroy(this);
}
if(mReactRootView ! =null) { mReactRootView.unmountReactApplication(); }}Copy the code
- 4. Open RN’s Developer menu
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager ! =null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
Copy the code
3.4 Handling Android related errors
- 1. So library conflict
Solution: Add the following Settings in build.gride under app
packagingOptions {
pickFirst 'lib/x86/libgnustl_shared.so'
pickFirst 'lib/armeabi-v7a/libgnustl_shared.so'
}
Copy the code