本文的前提是電腦已經(jīng)安裝過React-Native
相關(guān)環(huán)境和cocoapods
STEP 1 安裝node_modules包
創(chuàng)建package.json
文件
在項目的根目錄下圆米,這是為工程添加依賴庫。里面有工程的版本信息和所需要的依賴庫夺姑,第三方庫等
偷懶的做法是直接輸入命令
react-native init HelloWord
然后打開HelloWord根目錄的 package.json
文件 將HelloWord
改成你的APP名字
{
"name": "HelloWord",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "15.4.2",
"react-native": "0.41.2"
},
"devDependencies": {
"babel-jest": "19.0.0",
"babel-preset-react-native": "1.9.1",
"jest": "19.0.2",
"react-test-renderer": "15.4.2"
},
"jest": {
"preset": "react-native"
}
}
然后在項目的根目錄下
npm install
STEP 2 添加pod所需要的庫到工程
創(chuàng)建podfile
文件讲竿,利用Cocoapods安裝podfile中所涉及到的庫
target 'YourProjectName' do
#你的其他第三方依賴#
pod ‘React’, :path => ‘./node_modules/react-native’, :subspecs => [
‘Core’,
'ART',
'RCTActionSheet',
'RCTAdSupport',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
'RCTLinkingIOS',
]
end
然后進(jìn)行 pod install
安裝庫
pod install
STEP 3 創(chuàng)建index.ios.js文件
可以把剛才創(chuàng)建的HelloWord
中的index.ios.js
文件拿過來
但是記得修改index.ios.js
里面的工程名字
項目截圖.png
STEP 4添加到原生項目
在任意一個界面導(dǎo)入頭文件
#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"RN接入測試";
//手動設(shè)置IP
//RCTBundleURLProvider在接口中暴露了 jsLocation 屬性,可以通過 setJsLocation 手動設(shè)置IP。
//另需要在Info設(shè)置 NSAppTransportSecurity 的 NSAllowsArbitraryLoads 為 true 即可貌虾。
//RCTBundleURLProvider 類做了一些消息和屬性的封裝,可以通過判斷是否DEBUG環(huán)境然后做不同的設(shè)置裙犹。
[[RCTBundleURLProvider sharedSettings] setDefaults];
#if DEBUG
[[RCTBundleURLProvider sharedSettings] setJsLocation:@"192.168.1.211"];
#endif
NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL : jsCodeLocation
moduleName : @"buios"
initialProperties :nil
launchOptions : nil];
rootView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
[self.view addSubview:rootView];
}
到這里基本就結(jié)束了尽狠,但是現(xiàn)在運(yùn)行會提示服務(wù)器沒有打開,這時候在根目錄下npm start 開啟服務(wù)器伯诬,在運(yùn)行項目或者react-native run-ios
晚唇。就大功告成了。
簡單記錄一下自己實(shí)踐過有效的方式,自學(xué)扒資料好費(fèi)勁,如果有需要 XMG11期RN入門視頻的可以聯(lián)系我,感覺挺有用的