七牛的图片在这里竟然显示不了... 能够到简书上看图node
没事写个记录, 也算是温故而知新吧. 以下效果:react
react-native-cli和npm安装不在本文范围.如下react native简称RN.ios
如今RN也愈来愈方便了,集成进原生项目也很是简单.就这下面几个步骤.git
咱们有一个iOS原生项目叫 Helloworld, 是使用Cocoapods作包管理, RN也是Cocoapods接入. 目录结构以下:github
在项目目录下建立reactnative
文件夹, 在这个文件夹里建立两个文件index.ios.js
和package.json
;npm
package.json
添加如下内容json
{ "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
添加如下内容react-native
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
babel
打开项目中的Podfile
文件, 添加如下内容:ide
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 =>
后面的路径是否正确.
在项目下执行命令: pod install
RN是以view的形式在项目中使用的, 因此再项目中新建一个控制器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
在项目info.plist加上 App Transport Security Settings
:
在Build Phases
中添加一个Run Script
, 注意其中的路径正确:
在reactnative
文件夹下用终端命令: npm start
运行项目,不出意外就大功告成了.
最后项目目录结构: