前言
一般我們使用 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 包
- 把前端弄好的 bundle 包拉到項(xiàng)目中。
- 使用
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