1.创建一个原生项目
创建ios文件夹,将项目所有原生文件移到下面
创建ReactComponent文件夹,放置react-native相关文件
2.通过pod创建React-native
取决于你的工程如何组织,你的node_modules文件夹可能会在别的地方。
请将:path后面的内容修改为正确的路径。
target 'React_Combine' do
pod 'React', :path => '../ReactComponent/node_modules/react-native', :subspecs => [
'Core',
'RCTImage',
'RCTNetwork',
'RCTText',
'RCTWebSocket',
# 添加其他你想在工程中使用的依赖。
#path后面的路径需要根据实际项目目录结构进行修改
]
end
3.创建index.ios.js
import React, { Component } from 'react';
import {
AppRegistry, //注册
StyleSheet, //样式
Text, //文本组件
View, //视图组件
TextInput,
Image,
ScrollView,
ListView,
Button,
Navigator,
TouchableOpacity,
AlertIOS,
} from 'react-native';
//ES 5写法
var SimpleApp = React.createClass({
//不可改变的值
getDefaultProps(){
return{
age:18,
}
},
//可以改变的值
getInitialState(){
return{
title:'不透明触摸',
person:'张三',
}
},
render() {
return (
this.activeEvent('点击')}
onPressIn={()=>this.activeEvent('按下')}
onPressOut={()=>this.activeEvent('抬起')}
onLongPress={()=>this.activeEvent('长按')}
>
常用事件
{this.state.title}
{this.state.person}
{this.props.age}
);
},
//当按下鼠标
renderPress(){
console.log("按下鼠标");
AlertIOS.alert("按下鼠标");
},
activeEvent(event){
this.setState({
title:event,
person:'李四'
})
//拿到view
this.refs.topView
this.refs.commonEvent
},
});
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
},
innerViewStyle:{
backgroundColor:'orange',
}
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
4.在ViewController添加自定义的控件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch begin-----");
NSURL *jsCodeLocation = [NSURL
URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL : jsCodeLocation
moduleName : @"SimpleApp"
initialProperties :
@{
@"scores" : @[
@{
@"name" : @"Alex",
@"value": @"42"
},
@{
@"name" : @"Joel",
@"value": @"10"
}
]
}
launchOptions : nil];
UIViewController *vc = [[UIViewController alloc] init];
vc.view = rootView;
[self presentViewController:vc animated:YES completion:nil];
}
5.更新App Transport Security
修改ATS,info.plist文件
NSAppTransportSecurity NSExceptionDomains localhost NSTemporaryExceptionAllowsInsecureHTTPLoads
6.启动开发服务器
cd node_modules/react-native
npm run start
参照:
http://reactnative.cn/docs/0.24/embedded-app-ios.html#content