今天周末,弄弄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導入下面的庫:
1 platform :ios, "8.0" 2 use_frameworks! 3 target "XXXXXXXX" do 4 # 取決於你的工程如何組織,你的node_modules文件夾可能會在別的地方。 5 # 請將:path后面的內容修改為正確的路徑(一定要確保正確~~)。 6 pod 'React', :path => './ReactComponent/node_modules/react-native', :subspecs => [ 7 'Core', 8 'RCTActionSheet', 9 'RCTGeolocation', 10 'RCTImage', 11 'RCTNetwork', 12 'RCTPushNotification', 13 'RCTSettings', 14 'RCTText', 15 'RCTVibration', 16 'RCTWebSocket' 17 ] 18 end
成功如圖:
4.使用Xcode打開項目:先新建一對RNViewController文件作為承載react native界面,其中,RNViewController.m如下所示:
1 // 2 // RNViewController.m 3 // NativeAddRN 4 // 5 // Created by Shaoting Zhou on 2017/2/10. 6 // Copyright © 2017年 9elephas. All rights reserved. 7 // 8 9 #import "RNViewController.h" 10 #import <React/RCTRootView.h> 11 12 @interface RNViewController () 13 14 @end 15 16 @implementation RNViewController 17 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 21 NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"; 22 NSURL * jsCodeLocation = [NSURL URLWithString:strUrl]; 23 24 RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation 25 moduleName:@"NativeAddRN" 26 initialProperties:nil 27 launchOptions:nil]; 28 self.view = rootView; 29 // Do any additional setup after loading the view. 30 } 31 32 - (void)didReceiveMemoryWarning { 33 [super didReceiveMemoryWarning]; 34 // Dispose of any resources that can be recreated. 35 } 36 37 /* 38 #pragma mark - Navigation 39 40 // In a storyboard-based application, you will often want to do a little preparation before navigation 41 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 42 // Get the new view controller using [segue destinationViewController]. 43 // Pass the selected object to the new view controller. 44 } 45 */ 46 47 @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