React Native在Android當中實踐(一)——背景介紹
React Native在Android當中實踐(二)——搭建開發環境
React Native在Android當中實踐(三)——整合到Android專案當中
React Native在Android當中實踐(四)——程式碼整合
React Native在Android當中實踐(五)——常見問題
整合到Android專案當中
安裝JavaScript依賴包
在專案根目錄下建立一個名為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"
}
}
複製程式碼
version欄位沒有太大意義(除非你要把你的專案釋出到npm倉庫)。scripts中是用於啟動packager服務的命令。dependencies中的react和react-native的版本取決於你的具體需求。一般來說我們推薦使用最新版本。 可以使用 npm info react 例如:


來檢視當前的最新版本。另外,react-native對react的版本有嚴格要求,高於或低於某個範圍都不可以。 除此之外還有一種方式建立package.json 在Android Studio的下開啟Terminal命令列,輸入npm init 如圖






我們會發現目錄當中增加一個 /node_modules 資料夾,裡面是所有需要的 JavaScript 依賴,可以開啟檢視一下,內容非常多。

dependencies {
...
compile "com.facebook.react:react-native:+" // From node_modules.
}
複製程式碼
如果想要指定特定的React Native版本,可以用具體的版本號替換 +,當然前提是你從npm裡下載的是這個版本 。 接下來在專案中的build.gradle 檔案中為 React Native 新增一個 maven 依賴的入口,必須寫在 "allprojects" 程式碼塊中: 例如:
allprojects {
repositories {
...
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
...
}
複製程式碼
注意這裡的"$rootDir/../node_modules/react-native/android"必須寫對了 如果路徑寫錯了在執行Gradle同步構建的時候就會丟擲“Failed to resolve: com.facebook.react:react-native:0.x.x" 異常。 檢視專案中有node_modules,說明react和react native 安裝完成。 ######新增.flowconfig 下載flowconfig檔案
curl
-o .flowconfig [https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig](https://link.jianshu.com/?t=https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig)
複製程式碼
在專案根目錄新增.flowconfig 也可以手動建立在瀏覽器 raw.githubusercontent.com/facebook/re… 網址複製內容建立檔案 新增
"start": "node node_modules/react-native/local-cli/cli.js
複製程式碼
到package.json檔案下scripts標籤 修改前 如圖

