沒事寫個(gè)記錄, 也算是溫故而知新吧. 如下效果:
react-native-cli和npm安裝不在本文范圍.以下react native簡稱RN.
現(xiàn)在RN也越來越方便了,集成進(jìn)原生項(xiàng)目也非常簡單.就這下面幾個(gè)步驟.
我們有一個(gè)iOS原生項(xiàng)目叫 Helloworld, 是使用Cocoapods做包管理, RN也是Cocoapods接入. 目錄結(jié)構(gòu)如下:
[圖片上傳失敗...(image-145ea0-1516158368187)]
1.創(chuàng)建RN
在項(xiàng)目目錄下創(chuàng)建
reactnative
文件夾, 在這個(gè)文件夾里創(chuàng)建兩個(gè)文件index.ios.js
和package.json
;-
package.json
添加以下內(nèi)容{ "name": "Helloworld", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start" }, "dependencies": { "react": "15.3.1", "react-native": "^0.33.0" }, "devDependencies": { "babel-plugin-transform-decorators-legacy": "^1.3.4" } }
-
index.ios.js
添加以下內(nèi)容import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, } from 'react-native'; class Main extends Component { render() { return ( <View style={{backgroundColor:'yellow', flex:1, alignItems:'center', justifyContent:'center'}}> <Text>Hello World</Text> </View> ); } } AppRegistry.registerComponent('Helloworld', () => Main);
在
reactnative
文件夾下用終端命令:npm install
2.接RN入項(xiàng)目
-
打開項(xiàng)目中的
Podfile
文件, 添加以下內(nèi)容:pod 'React', :path => './reactnative/node_modules/react-native', :subspecs => [ 'Core', 'ART', 'RCTActionSheet', 'RCTAdSupport', 'RCTGeolocation', 'RCTImage', 'RCTNetwork', 'RCTPushNotification', 'RCTSettings', 'RCTText', 'RCTVibration', 'RCTWebSocket', 'RCTLinkingIOS', # Add any other subspecs you want to use in your project ]
注意
path =>
后面的路徑是否正確. 在項(xiàng)目下執(zhí)行命令:
pod install
-
RN是以view的形式在項(xiàng)目中使用的, 所以再項(xiàng)目中新建一個(gè)控制器
RNMainViewController
和RNView
RNMainViewController.m
#import "RNMainViewController.h" #import "ViewController.h" #import "RNView.h" @interface RNMainViewController () @end @implementation RNMainViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @"RN模塊首頁"; RNView * rnView = [[RNView alloc] initWithFrame:self.view.bounds]; self.view = rnView; } @end
RNView.m
#import "RNView.h" #import "RCTBundleURLProvider.h" #import "RCTRootView.h" @implementation RNView - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { #if TARGET_IPHONE_SIMULATOR [[RCTBundleURLProvider sharedSettings] setJsLocation:@"localhost"]; #else [[RCTBundleURLProvider sharedSettings] setDefaults]; #endif NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"Helloworld" initialProperties:nil launchOptions:nil]; [self addSubview:rootView]; rootView.frame = self.bounds; } return self; } @end
-
在項(xiàng)目info.plist加上
App Transport Security Settings
: -
在
Build Phases
中添加一個(gè)Run Script
, 注意其中的路徑正確:[圖片上傳失敗...(image-755f88-1516158368187)]
在
reactnative
文件夾下用終端命令:npm start
運(yùn)行項(xiàng)目,不出意外就大功告成了.