React Native 集成到原生項目(iOS)

想了好久,要先介紹各類組件的實際應用好,仍是先介紹怎麼把React Native集成到原生項目好。
由於想起,一旦開始寫各類組件的應用,就會花很長很長的篇幅,會把這個挺重要的內容拋到好遠,而集成到原生項目又是不少人所須要學習的(像我同樣哈,直接替代現有的項目是不科學的,做爲一個模塊集合進去才比較現實),因此決定了,仍是先花兩個篇章寫寫怎麼將React Native集成到原生項目以及JS與原生之間簡單的交互。node

因爲React並無假設你其他部分的技術棧——它一般只做爲MVC模型中的V存在——它也很容易嵌入到一個並不是由React Native開發的應用當中。實際上,它能夠和常見的許多工具結合,譬如CocoaPods。react

1、準備工做

1. React Native 開發基礎環境

這個能夠直接參考我寫的第二篇文章React Native 環境搭建和建立項目(Mac)。若是已經按上篇文章操做過,或者說已經在Mac平臺已經成功運行過React Native應用,那確定是已經有了開發基礎環境,能夠直接忽略這一步。ios

1) 安裝Node.js
方式一:
安裝 nvm(安裝嚮導在這裏)。而後運行命令行以下:git

nvm install node && nvm alias default node

這將會默認安裝最新版本的Node.js而且設置好命令行的環境變量,這樣你能夠輸入node命令來啓動Node.js環境。nvm使你能夠能夠同時安裝多個版本的Node.js,而且在這些版本之間輕鬆切換。
方式二:
先安裝Homebrew,再利用Homebrew安裝Node.js,運行命令行以下:github

//安裝Home-brew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
//安裝Node.js
brew install node

2) 安裝React Native的命令行工具(react-native-cli)npm

npm install -g react-native-cli

2. 安裝CocoaPods

本文只寫使用CocoaPods安裝React Native的方式,比較支持使用,也比較簡單直接。
若依舊不想使用CocoaPods,想直接集成的朋友能夠參考下面兩篇文章:
1)【iOS&Android】RN學習3——集成進現有原生項目
2) reactnative集成到原生ios項目 文中的手動集成react-nativejson

若是以前已經安裝並使用過CocoaPods,請忽略這一步(相信只要是iOS開發,必定大多數都接觸過了哈)。
若沒有安裝,則運行命令以下:react-native

gem install  cocoa pods
//權限不夠則運行下面一句
sudo gem install cocoapods

2、集成React Native

1. 安裝React Native

1)建立ReactComponent文件夾和配置文件ruby

在項目中建一個名爲ReactComponent的文件夾, 用於存放咱們react-native的相關文件, 再建立一個package.json文件, 用於初始化react-native.(文件夾名字自定義哈)
文件目錄結構以下:服務器

文件目錄結構1.png

建立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爲項目名稱。dependencies裏爲react和react-native的版本信息。
建議利用react-native init AwesomeProject新建新項目時會自動建立package.json,直接把文件複製過來,更改name爲本身的原生項目名,以確保react、和react-native的版本最新哈。

2)安裝React Native依賴包

在ReactComponent目錄下運行命令行:

npm install

運行效果以下:

npm install.png

這裏很須要耐心,曾經的我看着毫無反應的控制檯就放棄了n次。
可能靜下心去看部動漫回來就會發現它只想成功了。
實在install不回來的話,若是以前有建立過React Native項目,把裏面的node_modules直接拷貝過來,也是沒有問題(我的嘗試過)。

2. 建立 index.ios.js(js文件入口)

在ReactComponent文件夾裏建立index.ios.js文件,做爲js文件入口。

目錄結構2.png

index.ios.js文件內容以下:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class NativeRNApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

//  項目名要有所對應
AppRegistry.registerComponent('NativeRNApp', () => NativeRNApp);

3. Cocoapods集成React Native

若原項目無使用Cocoapods,則在根目錄下建立Podfile。(有則直接添加pod相關代碼)
目錄結構以下:

目錄結構3.png


Podfile文件內容爲(需確保路徑對):

platform :ios, 「7.0」

# 取決於你的工程如何組織,你的node_modules文件夾可能會在別的地方。
# 請將:path後面的內容修改成正確的路徑(必定要確保正確~~)。
pod 'React', :path => ‘./ReactComponent/node_modules/react-native', :subspecs => [
 'Core',
  'ART',
  'RCTActionSheet',
  'RCTAdSupport',
  'RCTGeolocation',
  'RCTImage',
  'RCTNetwork',
  'RCTPushNotification',
  'RCTSettings',
  'RCTText',
  'RCTVibration',
  'RCTWebSocket',
  'RCTLinkingIOS',
]
#須要的模塊依賴進來即可,這裏是爲了舉例子,列舉全部的模塊

而後在根目錄執行pod更新命令:

pod install

/*
如下是失敗狀況的處理
*/
//  pod命令過慢則可嘗試下面命令
pod install --verbose --no-repo-update

//  其中沒法正常下載pod install的解決方法:
(or更新最新的CocoaPods version: 0.39.0  查看方法 pod --version)
gem sources --remove https://rubygems.org/
gem sources -a 
gem sources -l 

# 注意 taobao 是 https; 
# gem若是版本太老能夠更新:sudo gem update --system; 
# 更新pod repo:pod repo update

運行效果:

pod install.png

3、原生項目處理

1. 向對應ViewController 添加RCTRootView

下面的ReactViewController是我建立的專門放React Native模塊的ViewController,有必要的話也可對RCTRootView進行進一步封裝(就不用每次都從新配置一次)。
ReactViewController代碼以下:

#import "ReactViewController.h"
#import <RCTRootView.h>

@interface ReactViewController ()

@end

@implementation ReactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";
    NSURL * jsCodeLocation = [NSURL URLWithString:strUrl];

    RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                         moduleName:@"NativeRNApp"
                                                  initialProperties:nil
                                                      launchOptions:nil];
    self.view = rootView;
    //  也可addSubview,自定義大小位置
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

項目結構以下:

項目結構.png

2. iOS項目更新App Transport Security

在iOS 9以上的系統中,除非明確指明,不然應用沒法經過http協議鏈接到localhost主機。 咱們建議你在Info.plist文件中將localhost列爲App Transport Security的例外。 若是不這樣作,在嘗試經過http鏈接到服務器時,會遭遇這個錯誤 - Could not connect to development server.

打開工程中的 Info.list 文件,添加下面配置便可:

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSExceptionDomains</key>
    <dict>
      <key>localhost</key>
      <dict>
       <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
       <true/>
      </dict>
    </dict>
  </dict>

配置效果以下:

App Transport Security配置.png

3. 啓動開發服務器

在運行咱們的項目以前,咱們須要先啓動咱們的開發服務器。進入 reactnative目錄 ,而後命令行啓動服務:

react-native start

4. 運行iOS項目

運行成功效果以下:

運行效果.png

能夠成功看到上面的界面,那就恭喜集成成功了。以前弄這個弄了一兩天,主要卡在npm install不回來那一步,而後pod是不可能的。。寫個更加詳細的教程但願你們能更輕鬆的把React Native集成到原生項目中哈,有問題歡迎留言哈。

目前暫時把demo打包到本身的百度雲(之後再想辦法放到github):
https://pan.baidu.com/s/1hrKnlvm

講完了怎麼把React Native集成到原生項目,下一篇打算寫React Native和原生項目之間的交互,而後還有好多好多和組件以及其它知識點都還沒寫,須要長期的堅持(😂略累),望支持♪───O(≧∇≦)O────♪

正在寫React Native的學習教程ing,是一邊研究一邊編寫的,已有的成果以下(不斷更新哈,望鼓勵):
1) React Native 簡介與入門
2) React Native 環境搭建和建立項目(Mac)
3) React Native 開發之IDE
4) React Native 入門項目與解析
5) React Native 相關JS和React基礎
6) React Native 組件生命週期(ES6)
7) React Native 集成到原生項目(iOS)
8) React Native 與原生之間的通訊(iOS)
9) React Native 封裝原生UI組件(iOS)

相關文章
相關標籤/搜索