七牛的图片在这里居然显示不了...
没事写个记录, 也算是温故而知新吧. 如下效果:
react-native-cli和npm安装不在本文范围.以下react native简称RN.
现在RN也越来越方便了,集成进原生项目也非常简单.就这下面几个步骤.
我们有一个iOS原生项目叫 Helloworld, 是使用Cocoapods做包管理, RN也是Cocoapods接入. 目录结构如下:
1.创建RN
在项目目录下创建
reactnative
文件夹, 在这个文件夹里创建两个文件index.ios.js
和package.json
;-
package.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
添加以下内容import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View,} from 'react-native';class Main extends Component { render() { return (
Hello World 在
reactnative
文件夹下用终端命令:npm install
2.接RN入项目
-
打开项目中的
Podfile
文件, 添加以下内容: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
运行项目,不出意外就大功告成了.
最后项目目录结构: