您的位置:首页 > Web前端 > React

iOS原生项目集成React Native模块

2017-02-13 08:30 337 查看
今天周末,弄弄Native和React Native之间的交互.首先,先在iOS原生项目中集成React Native模块:

注意事项:

1.因为react native的版本问题,部分细节可能有所不同,这里只介绍本猿的环境版本.

2.名称的一致性



1.首先,使用终端命令新建一个React Native项目待用;新建一个文件夹ReactComponent,把刚才新建的React Native项目中的index.ios.js和package.json和node_modules文件夹及其下属文件全都拖进文件夹ReactComponent.如:



图1

2.使用Xcode新建一个工程,把刚才的文件夹ReactComponent直接拖入到项目根目录下,简单粗暴.如图1.

3.使用cocoapods导入一些必须的库,其中Podfile中如下所示,接着pod install导入下面的库:

platform :ios, "8.0"
use_frameworks!
target "XXXXXXXX" do
# 取决于你的工程如何组织,你的node_modules文件夹可能会在别的地方。
# 请将:path后面的内容修改为正确的路径(一定要确保正确~~)。
pod 'React', :path => './ReactComponent/node_modules/react-native', :subspecs => [
'Core',
'RCTActionSheet',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket'
]
end


成功如图:



4.使用Xcode打开项目:先新建一对RNViewController文件作为承载react native界面,其中,RNViewController.m如下所示:

//
//  RNViewController.m
//  NativeAddRN
//
//  Created by Shaoting Zhou on 2017/2/10.
//  Copyright © 2017年 9elephas. All rights reserved.
//

#import "RNViewController.h"
#import <React/RCTRootView.h>

@interface RNViewController ()

@end

@implementation RNViewController

- (void)viewDidLoad {
[super viewDidLoad];

NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";
NSURL * jsCodeLocation = [NSURL URLWithString:strUrl];

RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"NativeAddRN"
initialProperties:nil
launchOptions:nil];
self.view = rootView;
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end


5.在Main.storyboard中新建一个Navigation Controller作为根,一个新的UIViewController绑定4中新建的RNViewController.再加上自带的UiViewController三者互相关联一下.如图:



最后,终端 cd ReactComponent文件夹下, npm start 启动服务即可.

效果如图:



demo源码下载: https://github.com/pheromone/IOS-native-and-React-native-interaction
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: