官方鏈接:reactnative.cn/docs/0.47/integration-with-existing-apps.html#content
1、創建一個根文件夾,里面創建一個字文件夾,命名ios
2、在根文件夾下創建一個package.json 文件,終端touch?package.json 就可以
{ "name": "MyReactNativeApp",
"version": "0.0.1", "private": true,
"scripts": { "start": "node node_modules/react-native/local-cli/cli.js start" },
"dependencies": { "react": "16.0.0-alpha.6", "react-native": "0.44.3" }
}
3、$ npm install ? ? 安裝JavaScript依賴包。(別告訴我你沒裝npm)
目前的目錄結構如下圖:
4、官方文檔建議大家使用cocoapods 來配置環境,so,你得裝個cocoapods,(聽人勸,吃飽飯!)
5、在 ios文件下,將我們的iOS工程拖進來。look,這里需要注意是將ios工程里的文件。我在測試的時候,將整個文件往里一丟,后續的配置中出現了很多問題。看了React Native 初始化項目的目錄結構,才發現不是這么回事。不多說了,看圖! 這樣的結構才能讓react-native run-ios 的時候找到 .xcodeproj 文件 能夠運行起來。
6、在 ios 文件下創建 Podfile文件,用來配置?所需要使用的 組件。
$vi Podfile ?
內容如下:
platform:ios,'8.0' ?#適配平臺
target 'TabBarTest' do ?#目標文件
# 'node_modules'目錄一般位于根目錄中
# 但是如果你的結構不同,那你就要根據實際路徑修改下面的`:path`
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'DevSupport', # 如果RN版本 >= 0.43,則需要加入此行才能開啟開發者菜單
'RCTText',
'RCTNetwork',
'RCTWebSocket', # 這個模塊是用于調試功能的
# 在這里繼續添加你所需要的模塊
]
# 如果你的RN版本 >= 0.42.0,則加入下面這行
pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
end
7、$pod install ? ? 沒有報錯的話,恭喜你,環境配置成功了!
8、在根目錄下,創建一個ios.index.js 文件,既然是混合開發,沒有點 js文件說不過去。代碼很簡單,如下:
'use strict'import React,{Component} from 'react';
import { AppRegistry, Text, View} from 'react-native';
class TestView extends Component{
????render(){
????????return(<Text>It is a text</Text>)
????}
}
AppRegistry.registerComponent('MyReactNativeApp',()=>TestView);
9、在xcode項目中,引用?#import <React/RCTRootView.h> 頭文件,用來裝 js 的頁面
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://host:8081/index.ios.bundle?platform=ios"];
//? ? NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL : jsCodeLocation
moduleName : @"MyReactNativeApp"
initialProperties :nil
launchOptions? ? : nil];
self.view = rootView;
ps:運行時產生以下錯誤:Could not connect to development server.?
Ensure?thefollowing:
-?Node?server?is?running?and?available?on?the?same?network?-?run'npm?start'from?react-native?root
-?Node?server?URL?is?correctly?set?in?AppDelegate
將host 切換成你本地的ip。
10、在根目錄下,啟動終端。$npm start ? 啟動開發服務器,這個終端是不能關閉的哦
11、可以通過Go2Shell (App Store 自行下載)重啟一個終端 $react-native run-ios ?運行iOS模擬器。
如果出現錯誤,$npm install 關閉終端重啟一下,在運行。
在環境配置的過程中可能出現很多問題,需要你安裝、升級一些文件。一般報錯問題,度娘都能解決的。
Good Luck ~