前言
- 本文基于React native 0.44.3
- 本文使用Pod方式
开始
1、创建package.json文件,配置类似如下(具体自己修改)
{
"name": "ReactHome",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "^16.0.0-alpha.6",
"react-native": "^0.44.3",
"react-native-update": "^4.0.6"
},
"devDependencies": {
"babel-jest": "21.2.0",
"babel-preset-react-native": "2.1.0",
"jest": "21.2.1",
"react-test-renderer": "16.0.0-alpha.6"
},
"jest": {
"preset": "react-native"
}
}
- PS:可以使用 npm init 来创建package.json
2、使用命令 npm install 来创建node_modules文件
3、创建index.ios.js 文件是RN程序的入口文件。例子index.android.js 文件如下:
import React,{Component} from 'react';
import {
AppRegistry,View,Text,
} from 'react-native';
class App extends Component{
//...其他方法
render(){
return(
<View>
<Text>this is React Native Page</Text>
</View>
);
}
//...其他方法
}
AppRegistry.registerComponent('XXX', () => App);
4、终端进入到项目根目录,执行 touch Podfile,在Podfile文件中填写内容大致如下:(xxx是项目名)
platform :ios, ‘8.0’
target ‘xxx’ do
pod 'React', :path => ‘./node_modules/react-native', :subspecs => [
'Core',
'ART',
'RCTActionSheet',
'RCTAdSupport',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
'RCTLinkingIOS',
‘RCTAnimation’,
]
pod ‘Yoga’, :path => ‘./node_modules/react-native/ReactCommon/yoga’
end
5、使用命令pod install
6、查看是否已添加依赖,下面图所示
image.png
7、创建显示Vct,例子如下
#import "RCTRootView.h"
@interface RNTestVct ()
@end
@implementation RNTestVct
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationController.navigationBar.hidden = YES;
//显示RN视
[self showReactNativeView]
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//显示RN视图
-(void) showReactNativeView
{
//用户的信息
NSDictionary *userInfo = @{@"name":@"Devil"};
//需要传递的数据
NSDictionary *paramsInfo = [[NSDictionary alloc] initWithObjects:@[userInfo] forKeys:@[@"userInfo"]];
//debug时服务器地址
NSString * jsCachePath = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";
//jsbundle地址
//本地打好离线包的位置// NSString *jsCachePath = [NSString stringWithFormat:@"%@/%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],@"ReactNativeBundle/index.ios.jsbundle"];
NSURL *jsCodeLocation = [NSURL URLWithString:jsCachePath];
RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"ReactHome" initialProperties:paramsInfo launchOptions:nil];
rootView.frame = [UIScreen mainScreen].bounds;
[self.view addSubview:rootView];
}
@end
8、测试
- 终端进入到项目根目录,执行 npm start
- 接着运行IOS项目即可
网友评论