7) React Native 整合到原生專案(iOS)

weixin_34337265發表於2016-08-13

想了很久,要先介紹各種元件的實際應用好,還是先介紹怎麼把React Native整合到原生專案好。
因為想起,一旦開始寫各種元件的應用,就會花很長很長的篇幅,會把這個挺重要的內容拋到好遠,而整合到原生專案又是很多人所需要學習的(像我一樣哈,直接替代現有的專案是不科學的,作為一個模組集合進去才比較現實),所以決定了,還是先花兩個篇章寫寫怎麼將React Native整合到原生專案以及JS與原生之間簡單的互動。


由於React並沒有假設你其餘部分的技術棧——它通常只作為MVC模型中的V存在——它也很容易嵌入到一個並非由React Native開發的應用當中。實際上,它可以和常見的許多工具結合,譬如CocoaPods。

一、準備工作

1. React Native 開發基礎環境

這個可以直接參考我寫的第二篇文章React Native 環境搭建和建立專案(Mac)。如果已經按上篇文章操作過,或者說已經在Mac平臺已經成功執行過React Native應用,那肯定是已經有了開發基礎環境,可以直接忽略這一步。

1) 安裝Node.js
方式一:
安裝 nvm(安裝嚮導在這裡)。然後執行命令列如下:

nvm install node && nvm alias default node

這將會預設安裝最新版本的Node.js並且設定好命令列的環境變數,這樣你可以輸入node命令來啟動Node.js環境。nvm使你可以可以同時安裝多個版本的Node.js,並且在這些版本之間輕鬆切換。
方式二:
先安裝Homebrew,再利用Homebrew安裝Node.js,執行命令列如下:

//安裝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 install -g react-native-cli

2. 安裝CocoaPods

本文只寫使用CocoaPods安裝React Native的方式,比較支援使用,也比較簡單直接。
若依舊不想使用CocoaPods,想直接整合的朋友可以參考下面兩篇文章:
1)【iOS&Android】RN學習3——整合進現有原生專案

  1. reactnative整合到原生ios專案 文中的手動整合react-native

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

gem install  cocoa pods
//許可權不夠則執行下面一句
sudo gem install cocoapods

二、整合React Native

1. 安裝React Native

1)建立ReactComponent資料夾和配置檔案

在專案中建一個名為ReactComponent的資料夾, 用於存放我們react-native的相關檔案, 再建立一個package.json檔案, 用於初始化react-native.(資料夾名字自定義哈)
檔案目錄結構如下:


2428275-18e038df60112992.png
檔案目錄結構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

執行效果如下:

2428275-851c15485fade12e.png
npm install.png

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

2. 建立 index.ios.js(js檔案入口)

在ReactComponent資料夾裡建立index.ios.js檔案,作為js檔案入口。


2428275-d540af90895ed90a.png
目錄結構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相關程式碼)
目錄結構如下:


2428275-ff4d2011fe3acb25.png
目錄結構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

執行效果:


2428275-219466759b75f7f4.png
pod install.png

三、原生專案處理

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

專案結構如下:


2428275-dd81e339a97ef1c7.png
專案結構.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>

配置效果如下:


2428275-f655c8daeba202b1.png
App Transport Security配置.png

3. 啟動開發伺服器

在執行我們的專案之前,我們需要先啟動我們的開發伺服器。進入 reactnative目錄 ,然後命令列啟動服務:

react-native start

4. 執行iOS專案

執行成功效果如下:


2428275-1ee3e3448b7f88a9.png
執行效果.png

可以成功看到上面的介面,那就恭喜整合成功了。之前弄這個弄了一兩天,主要卡在npm install不回來那一步,然後pod是不可能的。。寫個更加詳細的教程希望大家能更輕鬆的把React Native整合到原生專案中哈,有問題歡迎留言哈。

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


因為沒繼續這方面的工作所以好久沒更新了,可能程式碼因為rn的更新會有些問題,最好更新下pod的版本,看看官方文件,看到評論裡有相應的討論,出現問題的朋友最好也看看評論哈哈,可能有解決綁法♪───O(≧∇≦)O────♪

已有的成果如下:
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)

相關文章