React Native整合到原生專案示例

躍然發表於2017-01-22

1.建立空專案

2.新增RN依賴包
React Native的植入過程同時需要React和React Native兩個node依賴包。

package.json
我們把具體的依賴包記錄在package.json檔案中。如果專案根目錄中沒有這個檔案,那就自己建立一個。

對於一個典型的React Native專案來說,一般package.json和index.ios.js等檔案會放在專案的根目錄下。而iOS相關的原生程式碼會放在一個名為ios/的子目錄中,這裡也同時放著你的Xcode專案檔案(.xcodeproj)。
下面是一個最簡單的package.json的內容示例。

示例中的version欄位沒有太大意義(除非你要把你的專案釋出到npm倉庫)。scripts中是用於啟動packager服務的命令。dependencies中的react和react-native的版本取決於你的具體需求。一般來說我們推薦使用最新版本。你可以使用npm info react和npm info react-native來檢視當前的最新版本。另外,react-native對react的版本有嚴格要求,高於或低於某個範圍都不可以。本文無法在這裡列出所有react native和對應的react版本要求,只能提醒讀者先嚐試執行npm install,然後注意觀察安裝過程中的報錯資訊,例如require react@某.某.某版本, but none was installed,然後根據這樣的提示,執行npm i -S react@某.某.某版本。

{
  "name": "myAppWithRNDemo",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "15.4.1",
    "react-native": "0.39.2"
  }
}

安裝依賴包
使用npm(node包管理器,Node package manager)來安裝React和React Native模組。這些模組會被安裝到專案根目錄下的node_modules/目錄中。 在包含有package.json檔案的目錄(一般也就是專案根目錄)中執行下列命令來安裝:

$ npm install

3.整合pod

 cd進入專案所在目錄,命令列操作
 pod init
 編輯Podfile檔案後執行命令:
 pod install

4.設定info.Plist檔案NSAppTransportSecurity屬性,以此支援http

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

5.建立一個index.ios.js檔案

# 在專案根目錄執行以下命令建立檔案:
$ touch index.ios.js

在index.ios.js檔案中編寫自己所需業務程式碼

6.在原生app新增RN入口

- (IBAction)enterRNViewBtnClicked:(id)sender {

    NSLog(@"High Score Button Pressed");
    NSURL *jsCodeLocation = [NSURL
                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation
                         moduleName        : @"Playground"
                         initialProperties : @{@"scores" :@[@{@"name" : @"Alex", @"value": @"42"},@{@"name" : @"Joel",@"value": @"10"}]}
                          launchOptions    : nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

注: moduleName引數要匹配index.ios.js檔案中註冊的名字

此處存在問題:可能報錯RCTRootView找不到,需要到專案設定檔案裡設定”${PODS_ROOT}/Headers/Public/React” non-recursive 為 recursive

7.進入node_modules所在目錄,啟動npm服務

npm start

8.執行專案即可

9.demo下載:
https://github.com/Joeyechang/myAppWithRNDemo

參考連結:

  1. 嵌入到現有原生應用

  2. 動畫

相關文章