前言
一般我們使用 rn 集成到我們現(xiàn)有的項目的情況是前端給我們把 js 寫好澈驼,打成一個 bundle 包肴焊,客戶端通過集成 rn 到現(xiàn)有項目中就可以去加載這個前端已經(jīng)寫好的 bundle 包,這樣一份代碼就可以供前端耿战,iOS 和 Android 使用。
一、 rn 初始化
1.配置好 package.json
image
- name:項目名稱
- version: 版本號
- react-native : rn 的版本號鱼喉,這個很重要,這個版本號一定要跟后面的資源包所使用的版本號一致,不然會出現(xiàn)本地rn版本號與資源包rn版本號不一致的問題扛禽。
2.初始化
- 把package.json放到該項目文件夾的一級目錄下锋边, cd 到該項目文件夾.
- 執(zhí)行
npm install
。 給大家附上 rn 的安裝指南
二编曼、使用 cocoapods 導入 rn 的庫
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'
# 添加你所需要的庫
]
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
之后豆巨,會在該目錄下生成一個叫 node_modules 的文件,一定要確認好該文件的路徑掐场,否則pod install
會出錯往扔。 - 執(zhí)行
pod install
。
PS:其實也可以直接從 node_modules 這個文件中拉取我們所需要的庫到項目中熊户,但是我們需要在 Xcode 配置一些信息萍膛,不然會編譯報錯,如果用 pod 去導入嚷堡, pod 會幫我們配置好所有的信息蝗罗,所以還是建議使用 pod 去導入。
三麦到、導入 bundle 绿饵,使用 rn 加載 bundle 包
- 把前端弄好的 bundle 包拉到項目中。
- 使用
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
不是指項目名拟赊,這是指的是 bundle 包中 index.js 組件注冊的名稱。
image