iOS---React Native 集成到現(xiàn)有項(xiàng)目

前言

一般我們使用 rn 集成到我們現(xiàn)有的項(xiàng)目的情況是前端給我們把 js 寫(xiě)好,打成一個(gè) bundle 包,客戶端通過(guò)集成 rn 到現(xiàn)有項(xiàng)目中就可以去加載這個(gè)前端已經(jīng)寫(xiě)好的 bundle 包,這樣一份代碼就可以供前端,iOS 和 Android 使用。

一、 rn 初始化

1.配置好 package.json

image
  • name:項(xiàng)目名稱
  • version: 版本號(hào)
  • react-native : rn 的版本號(hào),這個(gè)很重要,這個(gè)版本號(hào)一定要跟后面的資源包所使用的版本號(hào)一致,不然會(huì)出現(xiàn)本地rn版本號(hào)與資源包rn版本號(hào)不一致的問(wèn)題。

2.初始化

  • 把package.json放到該項(xiàng)目文件夾的一級(jí)目錄下, cd 到該項(xiàng)目文件夾.
  • 執(zhí)行npm install 。 給大家附上 rn 的安裝指南

二、使用 cocoapods 導(dǎo)入 rn 的庫(kù)

platform :ios, '8.0'

target 'rntest' do
#  pod "yoga", :path => "./node_modules/react-native/ReactCommon/yoga"
  pod 'React', :path => './node_modules/react-native', :subspecs => [
  'Core',
  'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
  'RCTText',
  'RCTNetwork',
  'RCTImage',
  'RCTWebSocket', # needed for debugging
  'CxxBridge'
  # 添加你所需要的庫(kù)
 ]
 pod 'DoubleConversion', podspec: './node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
 pod 'Folly', podspec: './node_modules/react-native/third-party-podspecs/Folly.podspec'
 pod 'GLog', podspec: './node_modules/react-native/third-party-podspecs/GLog.podspec'
 pod 'yoga', :path => './node_modules/react-native/ReactCommon/yoga'

end
  • npm install 之后,會(huì)在該目錄下生成一個(gè)叫 node_modules 的文件,一定要確認(rèn)好該文件的路徑,否則 pod install 會(huì)出錯(cuò)。
  • 執(zhí)行 pod install

PS:其實(shí)也可以直接從 node_modules 這個(gè)文件中拉取我們所需要的庫(kù)到項(xiàng)目中,但是我們需要在 Xcode 配置一些信息,不然會(huì)編譯報(bào)錯(cuò),如果用 pod 去導(dǎo)入, pod 會(huì)幫我們配置好所有的信息,所以還是建議使用 pod 去導(dǎo)入。

三、導(dǎo)入 bundle ,使用 rn 加載 bundle 包

  1. 把前端弄好的 bundle 包拉到項(xiàng)目中。
  2. 使用 RCTRootView 就可以加載 bunlde 包的內(nèi)容。
#import "ViewController.h"
#import <React/RCTRootView.h>
@interface ViewController ()
@property (nonatomic, strong)RCTRootView * rootView;
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   NSString *urlString = [[NSBundle mainBundle]pathForResource:@"ios" ofType:@"bundle"];
   NSURL *jsCodeLocation = [NSURL fileURLWithPath:urlString];
   
   self.rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"kiwi-react-native" initialProperties:nil launchOptions:nil];
   
   self.rootView.frame = CGRectMake(0, 22, self.view.frame.size.width, self.view.frame.size.height - 22);
   [self.view addSubview:self.rootView];
}


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


@end

<br />

  • 注意 :[[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"kiwi-react-native" initialProperties:nil launchOptions:nil]; 中的 moduleName 不是指項(xiàng)目名,這是指的是 bundle 包中 index.js 組件注冊(cè)的名稱。
    image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容