在現有項目中集成React Native

大家基本都在維護之前的項目,如何在現有的項目中集成React Native是最容易遇到的問題。

集成到 iOS 應的主要步驟:

配置好 React Native 依賴和項目結構。瞭解你要集成的 React Native 組件。使用 CocoaPods 把這些組件以依賴的形式加入到項目中。創建 js 文件,編寫 React Native 組件的 js 代碼。在應用中添加一個RCTRootView。這個RCTRootView正是用來承載你的 React Native 組件的容器。啟動 React Native 的 Packager 服務,運行應用。驗證這部分組件是否正常工作。

一、在項目的目錄下創建一個文件夾:ReactNative。

然後創建package.json,搭建React Native環境

{ "name": "APPName", "version": "1.1.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start" }, "dependencies": { "react": "16.2.0", "react-native": "0.53.3" } }

使用npm install 安裝。

安裝成功後,在當前文件夾下,就會出現一個新的/node_modules文件夾,這個文件夾內存儲了所有的JS依賴.

二、配置CocoaPods依賴

比如:

pod 'React', :path => "./ReactNative/node_modules/react-native", :subspecs => [ 'Core', 'DevSupport', # 開啟開發者菜單 'RCTText', 'RCTImage', 'RCTNetwork', 'RCTActionSheet', 'RCTPushNotification', 'RCTWebSocket', # 這個模塊是用於調試功能的 'BatchedBridge' # 解決編譯錯誤 ] pod "yoga", :path => "./ReactNative/node_modules/react-native/ReactCommon/yoga"

然後執行執行pod install

二、

在項目根目錄下創建一個空的index.ios.js文件。

index.ios.js作為入口文件,一般用於註冊輸出JS文件的其他組件,也就是JS各個頁面的入口,內容大致如下,可以註冊多個文件用於多個頁面顯示.

import { AppRegistry } from 'react-native' import A from './AAA' import B from './BBB' AppRegistry.registerComponent('Aname', () => A) AppRegistry.registerComponent('Bname', () => B)

為了避免index.ios.js文件太大,閱讀性差,我們會把對應的組件代碼分到各個.js文件中.如上我們創建了一個AAA.js, 給個模板:

import React from 'react'; import { StyleSheet, Text, View} from 'react-native'; export default class AAA extends React.Component { render() { var contents = this.props['scores'].map((score) => ( {score.name}:{score.value} {'\n'} )); return ( 2048 High Scores! {contents} ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFFFFF', }, highScoresTitle: { fontSize: 20, textAlign: 'center', margin: 10, }, scores: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });

四、下面我們把寫好的js放到我們原生中顯示出來。

@implementation ReactTestViewController - (void)viewDidLoad { [super viewDidLoad]; NSString * strUrl = @"http://localhost:8081/index.bundle?platform=ios"; NSURL * jsCodeLocation = [NSURL URLWithString:strUrl]; RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"XingHuoLender" initialProperties:nil launchOptions:nil]; self.view = rootView; } @end

如果要傳參的話就使用:

[[RCTRootView alloc] initWithBundleURL: jsCodeLocation moduleName: @"Aname" initialProperties: @{ @"scores" : @[ @{ @"name" : @"Alex", @"value": @"42" } ] } launchOptions: nil];

其中jsCodeLocation,可以通過本地調試時,通過起服務,RN的端口號為8081來獲取.

第二種是通過main.jsbundle來獲取:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

moduleName就是 index.js 約定的組件名:

AppRegistry.registerComponent('Aname', () => AAA);

initialProperties為初始化屬性,這裡傳自己想要的值即可.傳到JS後,可以通過this.props來獲取,

五、

運行 npm start 開啟本地服務。

使用Xcode運行App。