今天周末,弄弄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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探