# React Native 的使用
## 安裝環(huán)境
### 1.安裝Homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
出了錯誤參見http://m.itdecent.cn/p/4e80b42823d5
### 2.安裝Node.js
brew install node
注意不要安裝 Node.js 的一個叫 n 的工具,沒有看錯,就是這個工具,別看著別的攻略安裝上了他,這玩意簡直噩夢。
### 3.安裝react-native-cli
npm install -g react-native-cli
若出現(xiàn)錯誤(可能由于權(quán)限不足),則用以下語句進(jìn)行安裝:
sudo npm install -g react-native-cli
如果需要換鏡像
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
### 4.選擇安裝Watchman Flow
有助于開發(fā),但是不安裝也沒問題,都是Facebook 提供的工具
brew install watchman
brew install flow
### 5.開發(fā)工具
VSCode
https://www.visualstudio.com/en-us/products/code-vs.aspx
### 6.創(chuàng)建項目
#### 6.1 單獨的項目
創(chuàng)建一個跨平臺的單獨項目
react-native init MyRN
稍等片刻 運行完畢后啟動他
cd MyRN
react-native run-ios
然后模擬器久啟動了
####6.2 在工程中加載RN
新建一個項目
項目根目錄下創(chuàng)建文件夾ReactComponent,
ReactComponent文件夾里面創(chuàng)建文件index.ios.js
內(nèi)容寫把剛才創(chuàng)建的MyRN 目錄下面的 index.ios.js 文件內(nèi)容考進(jìn)去 ,記得最下面名字和工程名字相同
ReactComponent 文件夾里面創(chuàng)建文件package.json
內(nèi)容:
{
"name": "MyRN",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-alpha.6",
"react-native": "0.44.3"
},
"devDependencies": {
"babel-jest": "20.0.1",
"babel-preset-react-native": "1.9.2",
"jest": "20.0.1",
"react-test-renderer": "16.0.0-alpha.6"
},
"jest": {
"preset": "react-native"
}
}
當(dāng)然也可以從剛才創(chuàng)建的項目拷貝 但是
"react": "16.0.0-alpha.6",
"react-native": "0.44.3"
如果更改的話可能出問題,盡量不要改
然后cd 到ReactComponent
執(zhí)行
npm install
執(zhí)行完畢 在 項目根目錄創(chuàng)建文件Podfile
內(nèi)容
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
target 'MyRN' do
pod 'Yoga', :path => './ReactComponent/node_modules/react-native/ReactCommon/yoga'
pod 'React', :path => './ReactComponent/node_modules/react-native', :subspecs => [
'Core',
'ART',
'RCTActionSheet',
'RCTAdSupport',
'RCTGeolocation',
'RCTImage',
'RCTNetwork',
'RCTPushNotification',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
'RCTLinkingIOS',
]
end
然后在項目根目錄執(zhí)行
pod install
如果pod 出錯請自行??pod 的出錯原因
cd 到 ReactComponent
執(zhí)行
react-native start
接著 打開xcode 在 ViewController.swift 的 viewDidLoad 方法寫上
let str = "http://localhost:8081/index.ios.bundle?platform=ios&dev=true"
let jsCodeLocation = URL(string: str)
let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "MyRN", initialProperties: [:], launchOptions: [:])
self.view = rootView
就可以運行了
這是我根據(jù)網(wǎng)上很多資料一步步嘗試的,嘗試過程中問題有很多,稍后再記錄。
特別注意的是 別用最新版本 !??!