# React Native 的使用
## 安裝環(huán)境
### 1.安裝Homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
出了錯(cuò)誤參見http://www.reibang.com/p/4e80b42823d5
### 2.安裝Node.js
brew install node
注意不要安裝 Node.js 的一個(gè)叫 n 的工具兑徘,沒有看錯(cuò)尸疆,就是這個(gè)工具,別看著別的攻略安裝上了他卡睦,這玩意簡(jiǎn)直噩夢(mèng)。
### 3.安裝react-native-cli
npm install -g react-native-cli
若出現(xiàn)錯(cuò)誤(可能由于權(quán)限不足)证薇,則用以下語(yǔ)句進(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)建項(xiàng)目
#### 6.1 單獨(dú)的項(xiàng)目
創(chuàng)建一個(gè)跨平臺(tái)的單獨(dú)項(xiàng)目
react-native init MyRN
稍等片刻 運(yùn)行完畢后啟動(dòng)他
cd MyRN
react-native run-ios
然后模擬器久啟動(dòng)了
####6.2 在工程中加載RN
新建一個(gè)項(xiàng)目
項(xiàng)目根目錄下創(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)建的項(xiàng)目拷貝 但是
"react": "16.0.0-alpha.6",
"react-native": "0.44.3"
如果更改的話可能出問題陆蟆,盡量不要改
然后cd 到ReactComponent
執(zhí)行
npm install
執(zhí)行完畢 在 項(xiàng)目根目錄創(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
然后在項(xiàng)目根目錄執(zhí)行
pod install
如果pod 出錯(cuò)請(qǐng)自行??pod 的出錯(cuò)原因
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
就可以運(yùn)行了
這是我根據(jù)網(wǎng)上很多資料一步步嘗試的,嘗試過程中問題有很多惋增,稍后再記錄叠殷。
特別注意的是 別用最新版本 !U┟蟆林束!