此文章非網(wǎng)上那些直接翻譯沒有經(jīng)過實(shí)踐的文章
項(xiàng)目Demo下載: http://pan.baidu.com/s/1dEZQWyH 密碼: m89h
第一部分:配置處理
1.CocoPods導(dǎo)入相關(guān)依賴庫(pod上面最新RN版本就0.13.0版本只支持ES5語法)
CocoPods是iOS/Mac開發(fā)中的包管理器,我們需要使用CocoaPods來進(jìn)行下載React Native嘶炭。(不會(huì)使用pod請百度)
當(dāng)你用CocoaPods進(jìn)行工作的時(shí)候届吁,需要往Podfile文件中添加如下的一些代碼信息,創(chuàng)建Podfile文件命令,先cd iOS項(xiàng)目根目錄再執(zhí)行命令.
touch Podfile
2.Podfile文件寫入相關(guān)代碼
Rn_iostaoge是原生項(xiàng)目名稱
platform :ios, ‘7.0’
target "Rn_iostaoge" do
pod 'React’
pod "React/RCTText"
pod "React/RCTActionSheet"
pod "React/RCTGeolocation"
pod "React/RCTImage"
pod "React/RCTLinkingIOS"
pod "React/RCTNetwork"
pod "React/RCTSettings"
pod "React/RCTVibration"
pod "React/RCTWebSocket"
end
3.創(chuàng)建React Native應(yīng)用(代碼是ES5語法,RN版本太低沒辦法)
創(chuàng)建index.ios.js在根目錄下
touch index.ios.js
index.ios.js寫入以下代碼
'use strict';
import React, {
Text,
View
} from 'react-native';
conststyles = React.StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red'
}
});
class SimpleApp extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>This is a simple application.</Text>
</View>
)
}
}
React.AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
上面代碼中的SimpeApp就是你的模塊名稱,原生iOS建立訪問鏈接的時(shí)候需要
第二部分:iOS原生項(xiàng)目需要做的處理
1.我們需要?jiǎng)?chuàng)建一個(gè)派生類ReactView 名字隨便起
在init...frame方法里寫入
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
NSURL *jsLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsLocation moduleName:@"SimpleApp" initialProperties:nil launchOptions:nil];
self.rootView = rootView;
[self addSubview:rootView];
}
return self;
}
2.在主窗口控制器里ViewDidLoad里聲明載入視圖(具體看Demo)
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ReactView *rootView = [[ReactView alloc]initWithFrame:CGRectMake(110, 110, 220, 220)];
[self.view addSubview:rootView];
}
3.啟動(dòng)React里的packager
cd進(jìn)入react目錄 執(zhí)行以下命令
npm run start
效果:
4.Command+R模擬器走起
效果: