/ios
目录,并拷贝iOS原生项目的全部工程文件到该目录下;/android
目录,并拷贝Android原生项目的全部工程文件到该目录下;package.json
文件,并添加以下内容:{
"name": "MyReactNativeApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
}
}
复制代码
yarn add react-native
或者npm i --save react-native
java
react-native
版本配套的react
能够根据步骤四中输出的警告信息查看,具体版本如:
warning "react-native@0.57.6" has unmet peer dependency "react@16.6.1".
或者直接查看react-native的package.json中依赖react的版本package.jsonnode
yarn add react@16.6.1
或 npm i --save react@16.6.1
react
注意:此处默认本机cocoapods已安装完成,未安装的可先google对应教程安装。参考:CocoaPods安装方法android
\ios
根目录下,终端执行pod init
,生成Podfile
文件;Podfile
文件,可参考以下配置:# 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
# 'node_modules'目录通常位于根目录中
# 可是若是你的结构不一样,那你就要根据实际路径修改下面的`:path`
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # 若是RN版本 >= 0.47则加入此行
'DevSupport', # 若是RN版本 >= 0.43,则须要加入此行才能开启开发者菜单
'RCTText',
'RCTNetwork',
'RCTWebSocket', # 调试功能须要此模块
'RCTAnimation', # FlatList和原生动画功能须要此模块
# 在这里继续添加你所须要的其余RN模块
'RCTActionSheet',
'RCTBlob',
'RCTGeolocation',
'RCTImage',
'RCTSettings',
'RCTVibration',
'RCTLinkingIOS',
]
# 若是你的RN版本 >= 0.42.0,则加入下面这行
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
# 若是RN版本 >= 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
复制代码
pod install
index.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}}>我是ReactNative !</Text> </View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:'green',
justifyContent:'center',
alignItems:'center'
}
});
AppRegistry.registerComponent("MyReactNativeApp", () => index);
复制代码
在须要跳转的页面(ViewController):ios
#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];
}
复制代码
Tips:若是遇到 以下错误c++
打开Build Phases→Link Binary With Libraries点击 + ,而后添加以下的.a
静态库git
dependencies {
implementation 'com.android.support:appcompat-v7:23.0.1'
...
implementation "com.facebook.react:react-native:+" // From node_modules
}
复制代码
若是想要指定特定的 React Native 版本,能够用具体的版本号替换 +,固然前提是你从 npm 里下载的是这个版本。github
allprojects {
repositories {
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
...
}
...
}
复制代码
确保依赖路径的正确!以避免在 Android Studio 运行 Gradle 同步构建时抛出 “Failed to resolve: com.facebook.react:react-native:0.x.x" 异常。objective-c
<uses-permission android:name="android.permission.INTERNET" />
复制代码
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
复制代码
ndk {
abiFilters "armeabi-v7a", "x86"
}
复制代码
缘由:
react-native生成aar的源码在npm install命令下载生成的 '$项目根目录'\node_modules\react-native\ReactAndroid
中,aar中关于对于CPU限制在 '$项目根目录'\node_modules\react-native\ReactAndroid\src\main\jni\Application.mk
, 在这个文件中,咱们能够到:npm
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 header
APP_CFLAGS := -Wall -Werror
APP_CPPFLAGS := -std=c++1y
APP_LDFLAGS := -Wl,--build-id
NDK_TOOLCHAIN_VERSION := 4.9
复制代码
说明了CPU的类型限定在了armeabi-v7a
和x86
上
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() {
return "MyReactNativeApp";
}
}
复制代码
Application
中实现ReactApplication
的方法,以下:@Override
public ReactNativeHost getReactNativeHost() {
return reactNativeHost;
}
private final ReactNativeHost reactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
@Override
protected String getJSMainModuleName(){
return "index";
}
};
复制代码
一、配置权限以便开发中的红屏错误能正确显示
若是你的应用会运行在 Android 6.0(API level 23)或更高版本,请确保你在开发版本中有打开悬浮窗(overlay)权限。你能够在代码中使用Settings.canDrawOverlays(this);来检查。之因此须要这一权限,是由于咱们会把开发中的报错显示在悬浮窗中(仅在开发阶段须要)。在 Android 6.0(API level 23)中用户须要手动赞成受权。具体请求受权的作法是在onCreate()中添加以下代码。其中OVERLAY_PERMISSION_REQ_CODE是用于回传受权结果的字段。
private final int OVERLAY_PERMISSION_REQ_CODE = 1; // 任写一个值
...
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);
}
}
复制代码
重写onActivityResult()
方法
@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
}
}
}
}
复制代码
若是你想在安卓 5.0 如下的系统上运行,请用
com.android.support:appcompat
包中的AppCompatActivity
代替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")
.setJSMainModulePath("index")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
// 注意这里的MyReactNativeApp必须对应“index.js”中的
// “AppRegistry.registerComponent()”的第一个参数
mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
}
复制代码
@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 boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
复制代码
处理:在app下的build.gride中添加以下设置
packagingOptions {
pickFirst 'lib/x86/libgnustl_shared.so'
pickFirst 'lib/armeabi-v7a/libgnustl_shared.so'
}
复制代码