React Native通过cocoaPods集成到现有iOS工程详解

一、集成便利

ReactNative对外提供一个View
CocoaPods支持ReactNative

二、集成需要环境

CocoaPods - gem install cocoapods
Node.js - brew install node

三、用CocosPod安装React

项目的根目录下 Podfile 文件:

platform:ios,'7.0'
use_frameworks!
target ‘kugou’ do
pod 'React'
pod 'React/RCTText'
pod 'React/RCTWebSocket'
end

终端输入命令:pod install --verbose --no-repo-update

安装成功后,打开workspace

结果:

四、工程配置

引入SDK:


User HeaderSearch Paths:

 

五、创建ReactNative页面

根 JavaScript 文件index.ios.js:

'use strict';
var React = require('react-native');
var {
  Text,
  View
} = React;
var styles = React.StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'red'
  }
});
class SimpleApp extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>111122222222222 哈哈哈哈哈哈 application.</Text>
      </View>
    )
  }
}
React.AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

最后一行的第一个‘SimpleApp’是模块名,后面会用到

六、引入React的View

#import "RCTRootView.h”

NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];
        // For production use, this `NSURL` could instead point to a pre-bundled file on disk:
        //
        //   NSURL *jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
        //
        // To generate that file, run the curl command and add the output to your main Xcode build target:
        //
        //   curl http://localhost:8081/index.ios.bundle -o main.jsbundle
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                            moduleName: @"kugou"
                                                     initialProperties:nil
                                                         launchOptions:nil];
[self addSubview:rootView];

七、启动开发服务器

因为是用自己的机器既做服务器有做客户端,所以也把程序根目录作为服务端服务的根目录;

终端cd进入工程根目录,在根目录创建目录ReactComponent作为运行服务的执行目录,输入命令:(JS_DIR=`pwd`/ReactComponent; cd Pods/React; npm run start -- --root $JS_DIR)

八、编译和运行

Command+R

修改js代码,直接Command+R就可以刷新页面了

九、版本发布

//OPTION 1 服务器上加载
NSURL *jsCodeLocation = [ NSURL URLWithString:@"http://localhost:8081/ 
index.ios.bundle?platform=ios&dev=true"]; 

 
//OPTION 2 本地加载
 NSURL *jsCodeLocation = [[ NSBundle mainBundle] URLForResource:@“testRN" withExtension:@“jsbundle”];
 

 
RCTRootView *rootView = [[ RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName: 
@“AwesomeProject" initialProperties:nil launchOptions:launchOptions]; 

十、集成后的性能指标

Size: 增加0.8M
Load Time:首次加载5s

十一、小技巧

提前初始化RCTRootView
多个jsbundle共用一个RCTRootView

posted @ 2016-04-11 11:02  yaozhx  阅读(3444)  评论(1编辑  收藏  举报