1.搭建开发环境
安装nvm, homebrew,node.js,react-native-cli,CocoaPods
2.安装React Native
可以去生成一个例子程序,然后把package.json文件拿过来
{
"name": "NativeRNApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "15.2.1",
"react-native": "0.29.2"
}
}
其中name就是项目名称,切换到项目目上一层目录,执行npm install命令
3.创建index.ios.js文件
同样可以是从生成的例子程序拷贝过来
4.CocoaPods集成React Native
platform :ios,’8.0’
target “testReact” do
pod 'React', :path => ‘/Users/liuyinghui/myFirstRectProject/node_modules/react-native', :subspecs => [
'Core',
'ART',
'RCTActionSheet',
'RCTAdSupport',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
'RCTLinkingIOS',
]
end
其中 target是你的项目名称,放到工程目录下。然后执行 pod install命令。
5.对原生项目进行修改
引入头文件
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"模块名称"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
CGRect rect=CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width , [UIScreen mainScreen].bounds.size.height);
self.window = [[UIWindow alloc] initWithFrame:rect];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController=rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
运行就可以了