React Native 与 App 集成方案

一、前言

Facebook提供了“Integrating with Existing Apps”方案,但是需要使用pod install, 会出现版本更新不及时。那么如何手动集成到Native代码中去呢?这里提供一个简单的Demo供参考。

二、构建步骤

  1. 1. 创建 React Native项目,目的是获取最新的React Native
  2. $ react-native init test
  3. 2. 创建 Native项目,例如ReactTest
  4. 3. test/node_modules拷贝到ReactTest根目录下
  5. 4. ReactTest项目中创建GroupLibraries
  6. 5. GroupLibraries中添加依赖的React Native项目:
  7. /node_modules/react-native/React/React.xcodeproj
  8. /node_modules/react-native/Libraries/Text/RCTText.xcodeproj
  9. /node_modules/react-native/Libraries/WebSocket/RCT WebSocket.xcodeproj
  10. 添加完成如下图

lesson9:React Native 与 App 集成方案 - 图1

  1. 6. Build Rules中添加静态库文件,如下图

lesson9:React Native 与 App 集成方案 - 图2

  1. 7.添加依赖循环
  2. $(SRCROOT)/node_modules/react-native/React
  3. 如下图所示:

lesson9:React Native 与 App 集成方案 - 图3

8.修改AppDelegate.m应用启动代码

  1. #import "AppDelegate.h"
  2. #import "ViewController.h"
  3. @interface AppDelegate ()
  4. @end
  5. @implementation AppDelegate
  6. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  7. if(!self.window){
  8. self.window = [[UIWindow alloc]init];
  9. }
  10. self.window.frame = [[UIScreen mainScreen]bounds];
  11. self.window.backgroundColor = [UIColor whiteColor];
  12. self.window.rootViewController = [ViewController new];
  13. [self.window makeKeyAndVisible];
  14. return YES;
  15. }

9.在ViewController.m中调用React Native和Native混编

  1. #import "ViewController.h"
  2. #import "RCTRootView.h"
  3. @interface ViewController ()
  4. @end
  5. @implementation ViewController
  6. - (void)viewDidLoad {
  7. [super viewDidLoad];
  8. UIButton *searchBtn = [[UIButton alloc]init];
  9. searchBtn.frame = CGRectMake(0 + 5, 0, 100, 100);
  10. searchBtn.backgroundColor = [UIColor colorWithRed:0.000 green:0.569 blue:1.000 alpha:1];
  11. [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
  12. [searchBtn setTitle:@"搜索" forState:UIControlStateHighlighted];
  13. NSURL *jsCodeLocation;
  14. jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
  15. RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
  16. moduleName:@"Study"
  17. initialProperties:nil
  18. launchOptions:nil];
  19. rootView.frame = [[UIScreen mainScreen]bounds];
  20. [self.view addSubview:rootView];
  21. [self.view addSubview:searchBtn];
  22. }
  23. - (void)didReceiveMemoryWarning {
  24. [super didReceiveMemoryWarning];
  25. // Dispose of any resources that can be recreated.
  26. }
  27. @end

10.还需要设置下Other Linker Flags, 如下图

lesson9:React Native 与 App 集成方案 - 图4

  1. 11. OK 享受编程吧