RN集成到現有原生應用-swift
1、配置項目目錄結構
創建一個空文件夾命名為你RN項目名稱,在里面再新建一個文件夾/ios
,把你現有的swift項目全部拷貝到/ios
文件夾內。
2、安裝 JavaScript 依賴包
在項目根目錄下創建一個名為package.json的空文本文件,內容如下:
{
"name": "SwiftRNProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "yarn react-native start"
}
}
3、安裝React、React Native模塊
接下來我們使用 yarn 或 npm(兩者都是 node 的包管理器)來安裝 React 和 React Native 模塊。請打開一個終端/命令提示行,進入到項目目錄中(即包含有 package.json 文件的目錄),然后運行下列命令來安裝:
$ yarn add react-native
這樣默認會安裝最新版本的 React Native,同時會打印出類似下面的警告信息(你可能需要滾動屏幕才能注意到):warning "react-native@0.52.2" has unmet peer dependency "react@16.2.0".
這是正?,F象,意味著我們還需要安裝指定版本的 React:
$ yarn add react@16.2.0
注意必須嚴格匹配警告信息中所列出的版本,高了或者低了都不可以。如果你使用多個第三方依賴,可能這些第三方各自要求的 react 版本有所沖突,此時應優先滿足react-native所需要的react版本。其他第三方能用則用,不能用則只能考慮選擇其他庫。
所有 JavaScript 依賴模塊都會被安裝到項目根目錄下的node_modules/目錄中(這個目錄我們原則上不復制、不移動、不修改、不上傳,隨用隨裝)。
把node_modules/目錄記錄到.gitignore文件中(即不上傳到版本控制系統,只保留在本地)。
4、配置 CocoaPods 的依賴
如果你的項目里面已經有了Podfile就直接配置,沒有就創建:
$ pod init
Podfile會創建在執行命令的目錄中。你需要調整其內容以滿足你的集成需求。調整后的Podfile的內容看起來類似下面這樣,下面是原生項目podfile必須添加的:
source 'https://github.com/CocoaPods/Specs.git'
# 對于Swift應用來說下面兩句是必須的
platform :ios, '8.0'
use_frameworks!
# target的名字一般與你的項目名字相同
target 'swift-2048' do
# 'node_modules'目錄一般位于根目錄中
# 但是如果你的結構不同,那你就要根據實際路徑修改下面的`:path`
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # 如果RN版本 >= 0.47則加入此行
'DevSupport', # 如果RN版本 >= 0.43,則需要加入此行才能開啟開發者菜單
'RCTText',
'RCTNetwork',
'RCTWebSocket', # 調試功能需要此模塊
'RCTAnimation', # FlatList和原生動畫功能需要此模塊
# 在這里繼續添加你所需要的其他RN模塊
]
# 如果你的RN版本 >= 0.42.0,則加入下面這行
pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
# 如果RN版本 >= 0.45則加入下面三個第三方編譯依賴
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end
創建好了Podfile后,就可以開始安裝 React Native 的 pod 包了。
$ pod install
5、創建RN組件
首先在項目根目錄下創建一個空的index.js文件。然后編寫你的組件。例子如下:
import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
class RNHighScores extends React.Component {
render() {
var contents = this.props['scores'].map((score) => (
<Text key={score.name}>
{score.name}:{score.value}
{'\n'}
</Text>
));
return (
<View style={styles.container}>
<Text style={styles.highScoresTitle}>2048 High Scores!</Text>
<Text style={styles.scores}>{contents}</Text>
</View>
);
}
}
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模塊的名稱
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);
RNHighScores是整體 js 模塊(即你所有的 js 代碼)的名稱。你在 iOS 原生代碼中添加 React Native 視圖時會用到這個名稱。
6、用RCTRootView加載RN組件
swift項目要先在橋接文件中導入#import <React/RCTRootView.h>
在ViewController
中先隨便添加一個按鈕,并綁定點擊事件:
@IBAction func highScoreButtonTapped(sender : UIButton) {
//這下面的jsCodeLocation是模擬器調試 如果是要真機調試一定要保證手機和電腦在同一個WiFi環境下,并把localhost替換為對應IP地址
//例如:let jsCodeLocation = URL(string: "http://192.168.79.90:8081/index.bundle?platform=ios")
let jsCodeLocation = URL(string: "http://localhost:8081/index.bundle?platform=ios")
let mockData:NSDictionary = ["scores":
[
["name":"Alex", "value":"42"],
["name":"Joel", "value":"10"]
]
]
let rootView = RCTRootView(
bundleURL: jsCodeLocation,
moduleName: "RNHighScores",
initialProperties: mockData as [NSObject : AnyObject],
launchOptions: nil
)
let vc = UIViewController()
vc.view = rootView
self.present(vc, animated: true, completion: nil)
}
注意info.plist中設置App Transport Security
7、運行項目
要運行應用,首先需要啟動開發服務器(即 Packager,它負責實時監測 js 文件的變動并實時打包,輸出給客戶端運行)。具體只需簡單進入到項目根目錄中,然后運行:
$ npm start
然后在Xcode中開始跑項目。