---
title: React Native學習筆記
tags: App, Front-end, React, React Native, 筆記
---
# React Native學習筆記
練習用備份:[react-native-practice](https://github.com/psli0101/react-native-practice)
[TOC]
## Install
### 前置作業
- 安裝 Android Studio (or Xcode)
- 安裝 Node.js 10+
- 推薦安裝 nvm 管理 Node 版本
- 安裝 npm or yarn
- 或是更建議兩個都有
- 部分套件用yarn安裝比較不會遇到Error
### Android 相關
- 安裝 adb
```
brew cask install android-platform-tools
```
- [Android Studio Emulator
](https://docs.expo.io/versions/v33.0.0/workflow/android-studio-emulator/)
### 安裝 React Native
```-
npm install -g react-native-cli
```
```-
react-native init sample
cd ./sample
# choose android or ios
react-native run-android
react-native run-ios
```
**注意:run之前,請先從 Android Studio 打開一個 Device**
### Other
- 自動刷新
- [How to enable live reload in react native on android?](https://stackoverflow.com/questions/36933287/how-to-enable-live-reload-in-react-native-on-android)
- 重新run react native之後需要再設定。
-
### React Native & Expo
RN官方現在提供兩個版本:Expo Cli 跟 React Native Cli。
Expo:
- 不需要安裝Android Studio或Xcode
- 內建常用套件
- 執行環境需要下載Expo的App
React Native Cli:
- 要安裝Android Studio跟Xcode
- 套件要自己找QQQQQ
很多人說Expo跑App比較方便,裝Expo官方App、掃掃QRcode就好,但個人是覺得用Android Studio的模擬器或是連手機還比較方便。~~在裝 Expo 時,不能直接跑非得要去裝個App不可,就不是很想用了。~~
看起來 Expo 比較簡單快速,但考量擴展性,使用 React Native Cli 比較有彈性(?)。
Expo 的特色就是一個Javascript打天下,沒有在分Android還iOS;React Native Cli 分出 Android 跟 iOS 兩個資料夾,遇到需要因應系統更動的部分,就能各自改各自的。
## 架構配置
### 寫作規則
```javascript=
import React, { Component } from 'react';
// Anything else you want to import
export default class ClassName extends Component {
constructor() {
super();
}
// Functions & Lifecycle
render() {
return (
// View
);
}
}
const styles = StyleSheet.create({
// Style
});
```
### Project-level
```
.
├── __tests__/
├── android/
├── ios/
├── node_modules/
├── src/
├── README.md
├── app.json
├── index.js
├── babel.config.js
├── metro.config.js
├── package-lock.json
├── package.json
└── yarn.lock
```
### src/
```
.
├── assets/ # ICON, 圖檔
├── components/ # 元件
├── constants/ # 常用參數
├── containers/ # Layout, Pages
├── redux/
├── router/
├── services/ # 常用功能,ex: Notification
└── App.js
```
- package.json: 命名常常會出現在各地被import的資料夾,可以避免無限 ``../`` 到不知道在幹嘛。
### Router & Navigation
[从react-navigation转react-router
](https://www.jianshu.com/p/ef12e91b25b3)
[React-Navigation](https://reactnavigation.org/):官方建議
[RNRF](https://github.com/aksonov/react-native-router-flux):基於React-Navigation的API
```-
yarn add react-navigation
yarn add react-native-gesture-handler
react-native link react-native-gesture-handler
```
> 看到一堆說react-navigation官方不支援redux所以不要用。
> 明明還是能用。
>
- createStackNavigator
- createTabNavigator
- createAppContainer:
- 將設定的 Navigator 實體化。
- withNavigation
BackHandle:
[this.props.navigation](https://reactnavigation.org/docs/en/navigation-prop.html)
傳值:
- ``this.props.navigation.navigate('RouteName', { // params... })``: 傳
- ``this.props.navigation.getParam('key', default value)``: 接
### [Redux & Redux-Saga & Redux-Thunk](https://hackmd.io/@psli0101/ryZlSuHfr)
[Redux](https://redux.js.org/):官方建議
- [React Native Redux 學習筆記
](https://yiyingloveart.blogspot.com/2016/06/react-native-redux.html)
- [Getting started with React Native and Redux](https://blog.cloudboost.io/getting-started-with-react-native-and-redux-6cd4addeb29)
- [How to use redux thunk in React and React Native](https://medium.com/@alialhaddad/how-to-use-redux-thunk-in-react-and-react-native-4743a1321bd0)
- 毋是一定唉配react,不過其設計理念是源自Flux,然後Flux又是為管理React資料流設計的,所以更傾向和react組官配。
- Vue也可以用,不過中國人表示他們家Vue跟他們家Vuex比較合。
- Vue跟React設計理念不一樣(研究ing)
[Redux Thunk](https://github.com/reduxjs/redux-thunk):
- 處理非同步 action 的 middleware。
-
[Redux Saga](https://github.com/redux-saga/redux-saga):
- 處理非同步 action 的 library。
非同步Action:
- 資料流
- thunk可以跟saga或其他library混用,他們的設計跟要解決的問題不一樣。
[Redux -> Redux-thunk -> Redux-Saga 實作筆記 — 1](https://medium.com/@Whien/redux-redux-thunk-redux-saga-%E5%AF%A6%E4%BD%9C%E7%AD%86%E8%A8%98-1-db59eb9103d7)
## React Native & Android & Web
React Native 預設排版方向是垂直的,和 Android 預設方向一樣。這點跟 Web 剛好相反,Web 預設方向是水平。
React Native 的標籤相當於寫 Android Layout 時拉的XML,和寫網頁時不一樣,不能使用HTML標籤。
### Lifecycle
有點奇怪,React元件的生命週期和寫Android或是Vue不太一樣@@
[React Life Cycle 生命週期更新版,父子元件執行順序](https://iandays.com/2018/07/27/reactlife/index.html)
[react life Cycle sample](https://codesandbox.io/s/xp7lk14x4w)
分三個部分:Mounting、Updating、Unmounting。
**Mounting**
Component建立後開始執行,
- constructor(props):
- getDerivedStateFromProps(nextProps, prevState):
-
**Updating**
發生Props變化時執行,
> 這個階段可能會因為頻繁更新Props,造成資源佔用,以至於效能降低。
>
**Unmounting**
App結束的時候執行,
[Sandbox](https://codesandbox.io/s/aged-fire-0lsti)
## Native Components
- **``<View>``**:
- 最基本的Component,相當於網頁的``<div>``標籤。
- 適用於需要排版的component,使用``<View>``有時候效果比``<Content>``好。
- 參考範例: [Edit](https://github.com/psli0101/react-native-practice/blob/master/src/components/toDoList/Edit.js)
- **``<Text>``**:
- 基本Component,放置文字。
- 也可以當按鈕、超連結。
- **``<Image>``**:
- **``<Button>``**:
- 不好用。
- **``Touchables``**:
- 自訂Button。
- **``<ScrollView>``**:
- 滾軸!!
- 部分Style不能使用
- **``<ListView>``**:
- 清單!!
### RN API
- Dimensions:
- 抓螢幕寬高。
- StyleSheet:
- 類CSS樣式表。
-
### Style
- React的style參數不是真的css,大小寫注意。
- 不是每個style參數都對每個元件有效。
- fontSize用在``<Text>``上有效。
- margin是對外,padding是對內。
- 善用常數設定,有益身心健康。
> 2019.07.12
> 如果把所有component的style(像是顏色、大小)都改用常數變數的方式設定,`asset/` 裡面可以新增一個 `style/` ,style檔案import到component裡,就能統一Project的設計風格而不用分散改。
>
> 不過考量到需要先設計完所有UI跟模組化所有會用到的元件,還要考慮哪些值是會重複使用的、哪些是共用的,有點麻煩@@,有閒再來試試。
>
- 透明度:
- 在顏色的色碼(六碼)後再加兩碼透明度十六進位碼。
- [如何設定字體的透明度?](https://blog.csdn.net/aiynmimi/article/details/80401883)
- [透明度的十六進位碼](https://blog.csdn.net/ouyang_peng/article/details/51896521)
[How to style the standard react-native android picker?](https://stackoverflow.com/questions/38921492/how-to-style-the-standard-react-native-android-picker/39141949#39141949)
### Native Base
```-
npm install native-base --save
```
像App版的Bootstrap,很多常用的Components。
[Native Base](https://nativebase.io/)
- **``<Container>``**:
- Header, Content, Footer。
-
- **``<Content>``**:
- 滾軸!!有滾軸!!!
- 內容區,基於``<ScrollView>``
- 預設為column,無法更改成row
- **``<Button>``**:
- 按鈕,比較像RN的``<TouchableOpacity>``。
- 可以自訂,也有提供類似Bootstrap的按鈕樣式。
-
## library
- [react-native-image-picker](https://github.com/react-native-community/react-native-image-picker)
- [刚刚在用的React Native的照相机和图片 react-native-image-picker](https://segmentfault.com/a/1190000015735377)
- 什麼都有。
- [react-native-camera](https://github.com/react-native-community/react-native-camera)
- [從0到1打造一款react-native App(三)Camera](https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/121888/)
- [RNCamera](https://github.com/react-native-community/react-native-camera/blob/master/docs/RNCamera.md)
- [官網](https://react-native-community.github.io/react-native-camera/)
- 偏向自訂,然後有一些寫好的辨識功能。
- 條碼掃描
- [react-native-push-notification](https://github.com/zo0r/react-native-push-notification)
- [install](https://hackmd.io/Bx0reMWiTuadZGNhSGRALQ)
- [How to Implement Push Notifications for iOS and Android In React Native](https://apiko.com/blog/react-native-push-notifications/)
- [Android >=8.0 不顯示notification的問題]()
- [react-native-firebase](https://github.com/invertase/react-native-firebase)
- [react-native-fs](https://github.com/itinance/react-native-fs)
- 好像是文件存取管理?
- 可以完成File的CRUD
- 不像image-picker一樣自帶選單component :(
- Example: [chjwrr/RN-react-native-fs](https://github.com/chjwrr/RN-react-native-fs/blob/master/index.ios.js)
-
## Example - ToDoList
![](https://i.imgur.com/46Mgag6.png)
![](https://i.imgur.com/oTS0lw3.png)
![](https://i.imgur.com/6TtamJC.png)
## QR code Scanner
### RNCamera
```javascript=
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.back}
onBarCodeRead={this.onBarCodeRead}
/>
```
- type: 鏡頭
- RNCamera.Constants.Type.back
- RNCamera.Constants.Type.front
- onBarCodeRead: 掃到條碼後怎麼處理
-
### Alert Dialog
```javascript=
import { StyleSheet, View, Text, Linking, Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
```
- Alert:
```javascript=
Alert.alert(
'Title',
'Message',
[
{text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{cancelable: false},
);
```
- Linking:
```javascript=
Linking.canOpenURL('https://')
.then(supported => {
if (!supported) {
console.log("Can't open");
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.error('An error occurred', err));
```
- canOpenURL: 指定URL格式,符合才能進 openURL。
- openURL: 開啟網頁。
- 處理資安問題。
## pull to refresh & infinite scroll
### RefreshControl
- [RefreshControl](https://facebook.github.io/react-native/docs/refreshcontrol.html)
- [Refresh Control with ListView Full Example](https://riptutorial.com/react-native/example/22714/refresh-control-with-listview-full-example)
-
### Infinite Scroll
- [Implementing an Infinite Scroll list in React Native](https://scotch.io/tutorials/implementing-an-infinite-scroll-list-in-react-native)
## Cookie
- [React Native Cookie使用指南](https://www.jianshu.com/p/9b72f94c432e)
- [react-native-cookies](https://github.com/joeferraro/react-native-cookies)
## 打包APK
[React Native App 實戰 (十) Android 打包 apk
](https://ithelp.ithome.com.tw/articles/10188858)
[Publishing to Google Play Store
](https://facebook.github.io/react-native/docs/signed-apk-android)
[[教學] 第一次上架就成功!只要這5個步驟,就能將你的React Native Android APP上架到Google Play](http://shubo.io/react-native-android-publish/)
## 問題集中
- ![](https://i.imgur.com/4Is5ldH.png)
- [SDK location not found.](https://stackoverflow.com/questions/32634352/react-native-android-build-failed-sdk-location-not-found)
- [error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually(ry](https://github.com/facebook/react-native/issues/25506)
- [常見ERROR](https://www.chuchur.com/article/react-native-android-error)
- ![](https://i.imgur.com/JHhwhav.png)
- [React native how to fix INSTALL_FAILED_UPDATE_INCOMPATIBLE ](https://gist.github.com/R4meau/1b595335657cd884c85983e53d7fd72a)
- ![](https://i.imgur.com/zeWVMlJ.png)
- 沒有link到
- link之後無法編譯請參見↓
- [if android cannot compile](https://github.com/react-native-community/react-native-camera/issues/2150)
- ![](https://i.imgur.com/WFAIrTC.png)
- [How to fix Execution failed for task ':app:processDebugManifest' in React Native?
](https://stackoverflow.com/questions/56644149/ho-to-fix-execution-failed-for-task-appprocessdebugmanifest-in-react-native)
- Build successful but App stop
- use ``adb logcat`` , check if your app have any error message.
- like this: ``Didn't find class "com.imagepicker.FileProvider" on path``
- 原因可能出在該套件需要的package你的開發環境並沒有,可以上網google看看有沒有人提及,或是官網找。
- ![](https://i.imgur.com/a2un0T7.png)
-
- [Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference](https://github.com/react-native-community/react-native-maps/issues/2924)
## Develop Tools
- [Day 27:React Native 除錯](https://ithelp.ithome.com.tw/articles/10188878)
- [Debugging · React Native - Facebook Open Source](https://facebook.github.io/react-native/docs/debugging)
- [10 React Developer Tools You Might Have Missed](https://medium.com/@jondot/10-react-developer-tools-you-might-have-missed-6c7575cc27eb)
## 參考資料
[React Native官方](https://facebook.github.io/react-native/)
[10+ Free React Native Templates to Kickstart Your App Development](https://www.codeinwp.com/blog/free-react-native-templates/)