此文章非网上那些直接翻译没有经过实践的文章
项目Demo下载: http://pan.baidu.com/s/1dEZQWyH 密码: m89h
第一部分:配置处理
1.CocoPods导入相关依赖库(pod上面最新RN版本就0.13.0版本只支持ES5语法)
CocoPods是iOS/Mac开发中的包管理器,我们需要使用CocoaPods来进行下载React Native。(不会使用pod请百度)
当你用CocoaPods进行工作的时候,需要往Podfile文件中添加如下的一些代码信息,创建Podfile文件命令,先cd iOS项目根目录再执行命令.
touch Podfile
2.Podfile文件写入相关代码
Rn_iostaoge是原生项目名称
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.创建React Native应用(代码是ES5语法,RN版本太低没办法)
创建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建立访问链接的时候需要
第二部分:iOS原生项目需要做的处理
1.我们需要创建一个派生类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.启动React里的packager
QQ20160719-1@2x.png
cd进入react目录 执行以下命令
npm run start
效果:
QQ20160719-3@2x.png
4.Command+R模拟器走起
效果:
QQ20160719-4@2x.png