Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native 結合 Redux 的專案開發實戰心得(一)

編輯:關於 Android 程式設計

寫在前面

前一陣子剛把以 Redux 為核心的單頁應用收尾,緊接著就投入到 React Native 的開發節奏裡。整個過程快得令人意外——短短一週,我們兩人分工協作就把 App 完成,而且同時跑通了 iOS 與 Android 兩大平台。第一輪內部測試下來,無論是流暢度還是整體使用體驗,表現都相當不理想之外的滿意。接下來幾篇,我會把開發過程中摸索到的技巧與踩過的坑逐一整理出來。

專案架構

與用 React 開發單頁應用不同,React Native 並不需要依賴 webpack,因為 Facebook 已經提供了一套以 NodeJS 為基礎的轉譯與執行工具,這裡就不再展開。整體目錄結構大致如下:

|---- project
     |---- android // Android 外殼
     |---- ios // iOS 外殼
     |---- node_modules // 依賴的 node 模組
     |---- app // 本專案的 JS 程式碼
     |---- actions // Redux 的 actions
     |---- assets // 專案使用的 icon
     |---- components // 自訂元件
     |---- containers // 容器頁面
     |---- mixins // 全域工具方法
     |---- modules // 全域自訂模組
     |---- reducers // Redux 的 reducers
     |---- configureStore.js // Redux store 設定
     |---- index.js // App 入口頁面
     |---- index.ios.js // iOS 入口
     |---- index.android.js // Android 入口
     |---- packge.json // 專案包資訊

若你對 Redux 還不熟悉,可以先參考我先前寫的《以 Redux 為基礎的單頁應用開發總結》。其實除了路由部分,其餘結構與單頁應用的差異並不大。

依賴的 Node 模組

開發 React Native 離不開 NodeJS 的支援。相較於單頁應用,這裡依賴的模組數量更少,除了 Redux 相關套件之外,其餘大多是專案中實際用到的第三方元件。

"dependencies": {
  "@remobile/react-native-toast": "^1.0.4", // 錯誤提示的小彈窗
  "base-64": "^0.1.0",
  "react": "^0.14.8",
  "react-native": "^0.25.1",
  "react-native-animatable": "^0.6.0", // 動畫庫
  "react-native-communications": "^2.0.0", // 調用手機通訊功能
  "react-native-image-picker": "^0.18.17", // 圖片選擇
  "react-native-modalbox": "^1.3.3", // 模態框
  "react-native-tab-navigator": "^0.2.18", // 導覽欄
  "react-native-viewpager": "^0.2.1", // 圖片輪播切換
  "react-redux": "^4.4.5",
  "redux": "^3.5.2",
  "redux-thunk": "^2.0.1"
}

錯誤提示

App 的錯誤提示與網頁略有不同。網頁寬度較大,錯誤訊息通常出現在輸入框後方,或懸浮於右上角;但在 App 裡,必須把使用者五花八門的螢幕尺寸考慮進去,因此錯誤訊息更適合放在一個相對獨立、又不會遮擋其他元素的區塊。目前主流的做法如下圖所示:

也就是懸浮在頁面中下方,並定時自動關閉。這種元件自己寫其實並不難,但為了省事以及更好的相容性,我直接使用第三方套件 @remobile/react-native-toast。

import Toast from '@remobile/react-native-toast';
// ...
Toast.showShortBottom('使用者名稱或密碼不正確');

它對外提供的 API 有下面幾個,從命名就能猜到用途:

Toast.showShortTop = function (message) { showToast(message, "short", "top"); };
Toast.showShortCenter = function (message) { showToast(message, "short", "center"); };
Toast.showShortBottom = function (message) { showToast(message, "short", "bottom"); };
Toast.showLongTop = function (message) { showToast(message, "long", "top"); };
Toast.showLongCenter = function (message) { showToast(message, "long", "center"); };
Toast.showLongBottom = function (message) { showToast(message, "long", "bottom"); };
Toast.show = function (message) { showToast(message, "short", "bottom"); };
Toast.hide = function () { RCTToast.hide(); };

安裝與使用方式請查閱官方文件。

動畫庫

我曾經花時間研究過 CSS3 的動畫庫,其實目前主流的動畫類型與創意就那麼多,有興趣的可以 clone 一下 myAnimate 這個專案。一句話總結:CSS3 裡能做的動畫方案,React Native 裡也幾乎應有盡有。我這邊採用的是 react-native-animatable 元件,用法如下:

import * as Animatable from 'react-native-animatable';
class ExampleView extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => this.setState({fontSize: (this.state.fontSize || 10) + 5 })}>
        Size me up, Scotty
      </TouchableOpacity>
    );
  }
}

下面是官方提供的 Demo:

調用手機通訊功能

要在 Hybrid App 裡實現這個功能還挺麻煩的,得由客戶端先封裝好介面給 H5 呼叫;而在 React Native 裡,一個元件就能搞定——react-native-communications,安裝方式請查閱官方文件。

這個元件安裝簡單,支援的功能包括:撥號、傳送簡訊、傳送 Email、開啟網頁等。下面是官方給出的一個綜合範例:

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import Communications from 'react-native-communications';
class RNCommunications extends Component {
  render() {
    return (
      <View>
        <TouchableOpacity onPress={() => Communications.phonecall('0123456789', true)}>
          <View><Text>Make phonecall</Text></View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.email(['emailAddress1', 'emailAddress2'], null, null, 'My Subject', 'My body text')}>
          <View><Text>Send an email</Text></View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.text('0123456789')}>
          <View><Text>Send a text/iMessage</Text></View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.web('https://github.com/facebook/react-native')}>
          <View><Text>Open react-native repo on Github</Text></View>
        </TouchableOpacity>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', backgroundColor: 'rgb(253,253,253)' },
  holder: { flex: 0.25, justifyContent: 'center' },
  text: { fontSize: 32 },
});
AppRegistry.registerComponent('RNCommunications', () => RNCommunications);

存取手機相簿

如何叫出手機相簿並上傳圖片,是個老生常談的問題。React Native 裡可以透過 react-native-image-picker 來處理,安裝方式請查閱官方文件。

擷取一段程式碼片段:

import ImagePicker from 'react-native-image-picker'
const options = {
  title: '選擇上傳圖片', // 傳入 null 或空字串可移除標題
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照...', // 傳入 null 或空字串可移除此按鈕
  chooseFromLibraryButtonTitle: '從相簿中選擇...', // 傳入 null 或空字串可移除此按鈕
  cameraType: 'back', // 'front' 或 'back'
  mediaType: 'photo',
  maxWidth: 200, // 僅限照片
  maxHeight: 200, // 僅限照片
  allowsEditing: true,
  noData: false,
}
// ...
onUpload() {
  ImagePicker.showImagePicker(options, (response) => {
    if (response.didCancel) {
      // 使用者取消
    } else if (response.error) {
      // 發生錯誤
    } else {
      let source = {uri: response.uri.replace('file://', ''), isLocal: true, isStatic: true};
      this.setState({ form: {...this.state.form, avatar: source} })
    }
  })
}

模態框

模態框在 App 裡使用頻率相當高,像是確認框、載入框、輸入框等等。兼顧良好的使用體驗與相容性,我在底層採用 react-native-modalbox,再依不同功能做二次加工。

ConfirmModal

這個很常見,就不多作介紹,複製下面程式碼即可直接使用。

import React, { Component } from 'react';
import { Dimensions, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import ModalBox from 'react-native-modalbox';
const styles = StyleSheet.create({
  modal: { borderRadius: 10 },
  modalContent: { flex: 1, paddingLeft: 10, paddingRight: 10 },
  h2: { marginTop: 15, fontSize: 20, color: '#555', textAlign: 'center' },
  modalOption: { flexDirection: 'row', borderTopWidth: 1, borderTopColor: '#ddd' },
  modalCancel: { flex: 1, padding: 15 },
  modalCancelText: { fontSize: 16, textAlign: 'center' },
  modalConfirm: { flex: 1, padding: 15, borderLeftWidth: 1, borderLeftColor: '#ddd' },
  modalConfirmText: { fontSize: 16, textAlign: 'center' },
  message: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  messageText: { color: '#555', fontSize: 16 },
});
export default class ConfirmModal extends Component {
  constructor(props) { super(props); }
  open() { this.refs.modal.open() }
  close() { this.refs.modal.close() }
  render() {
    let { width } = Dimensions.get('window');
    return (
      <ModalBox style={styles.modal} backdropOpacity={0.3} isOpen={false} position="center" ref="modal">
        <View style={styles.modalContent}>
          <Text style={styles.h2}>{ this.props.title || '提示' }</Text>
          <View style={styles.message}><Text style={styles.messageText}>{ this.props.message }</Text></View>
        </View>
        <View style={styles.modalOption}>
          <TouchableOpacity style={styles.modalCancel} onPress={() => this.refs.modal.close()}>
            <Text style={styles.modalCancelText}>取消</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.modalConfirm} onPress={() => this.props.onConfirm()}>
            <Text style={styles.modalConfirmText}>確定</Text>
          </TouchableOpacity>
        </View>
      </ModalBox>
    )
  }
}

LoadingModal

這個也很常見,一樣複製下面程式碼即可直接使用。

import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import ModalBox from 'react-native-modalbox';
const styles = StyleSheet.create({
  modal: { justifyContent: 'center', alignItems: 'center', backgroundColor: 'transparent' },
});
export default class LoadingModal extends Component {
  constructor(props) { super(props); }
  open() { this.refs.modal.open() }
  close() { this.refs.modal.close() }
  render() {
    return (
      <ModalBox style={styles.modal} animationDuration={10} backdrop={false} backdropOpacity={.3} backdropPressToClose={false} isOpen={this.props.isOpen} position="center" ref="modal">
      </ModalBox>
    );
  }
}

PickerModal

這個特別說明一下,PickerModal 主要用於處理頁面上的 Picker,顯示效果如下圖:

import React, { Component } from 'react';
import { Dimensions, StyleSheet, Text, TouchableOpacity, Picker, View } from 'react-native';
import ModalBox from 'react-native-modalbox'
import dismissKeyboard from '../mixins/dismiss-keyboard'
const styles = StyleSheet.create({
  popup: {},
  popupContent: { flex: 1, paddingLeft: 10, paddingRight: 10 },
  h2: { marginTop: 15, fontSize: 20, color: '#555', textAlign: 'center' },
  popupOption: { flexDirection: 'row', borderTopWidth: 1, borderTopColor: '#ddd' },
  popupCancel: { flex: 1, padding: 15 },
  popupCancelText: { fontSize: 16, textAlign: 'center' },
  popupConfirm: { flex: 1, padding: 15, borderLeftWidth: 1, borderLeftColor: '#ddd' },
  popupConfirmText: { fontSize: 16, textAlign: 'center' },
  message: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  messageText: { color: '#555', fontSize: 16 },
});
export default class PickerModal extends Component {
  constructor(props) { super(props); }
  open() { dismissKeyboard(); this.refs.modal.open() }
  close() { this.refs.modal.close() }
  render() {
    let { width } = Dimensions.get('window');
    return (
      <ModalBox style={styles.popup} backdropOpacity={0.3} isOpen={false} position="bottom" ref="modal" swipeToClose={false}>
        <View style={styles.popupContent}>
          <Picker>
            {this.props.dataSource.map((item, i) => {
              if (item.length) return <Picker.Item key={i} label={item[0]} value={item[1]} />
            })}
          </Picker>
        </View>
      </ModalBox>
    )
  }
}

補充說明一下 dismissKeyboard() 這個方法,它用來關閉頁面的鍵盤(keyboard)。React Native 預設沒有這種方法,需要自己撰寫:

import { TextInput } from 'react-native';
const { State: TextInputState } = TextInput;
export default function dismissKeyboard() {
  TextInputState.blurTextInput(TextInputState.currentlyFocusedField());
}

導覽欄

這個元件其實 React Native 提供了原生版本,但樣式和功能都不太好控制,建議自己手寫一個,程式碼如下:

import React, { Component } from "react";
import { Image, Platform, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const styles = StyleSheet.create({
  leftButton: { marginLeft: 5 },
  rightButton: { marginRight: 5 },
  button: { width: 44, height: 44, justifyContent: 'center', alignItems: 'center' },
  nav: { backgroundColor: '#f9f9f9', flexDirection: 'row', alignItems: 'center' },
  title: { flex: 1, height: 44, justifyContent: 'center' },
  btnText: { fontSize: 16, color: '#777' },
  marginForIOS: { marginTop: 20 },
  titleText: { fontSize: 20, textAlign: 'center', color: '#555' }
});
export class RightButton extends Component {
  render() {
    return (
      <TouchableOpacity style={styles.button} onPress={this.props.onPress}>
        { this.props.text ? <Text style={styles.btnText}>{this.props.text}</Text> : null }
        { this.props.icon ? <Image source={this.props.icon} /> : null }
      </TouchableOpacity>
    );
  }
}
export class NavigatorBar extends Component {
  _leftButton() {
    if (this.props.navigator.getCurrentRoutes().length > 1) return (
      <TouchableOpacity style={styles.button} onPress={() => this.props.navigator.pop()}>
        <Image source={require('../assets/icon-nav-left.png')} />
      </TouchableOpacity>
    )
  }
  _rightButton() {
    if (this.props.rightButton) return (<RightButton {...this.props.rightButton} />)
  }
  render() {
    return (
      <View style={styles.nav}>
        <View style={Platform.OS === 'ios' ? styles.marginForIOS : {}}>{this._leftButton()}</View>
        <View style={Platform.OS === 'ios' ? styles.marginForIOS : {}}><Text style={styles.titleText}>{ this.props.name }</Text></View>
        <View style={Platform.OS === 'ios' ? styles.marginForIOS : {}}>{this._rightButton()}</View>
      </View>
    );
  }
}

接著在 container 裡就能使用了:

import { NavigatorBar } from '../components/navigator'
// 沒有右側按鈕
<NavigatorBar name="登錄" navigator={this.props.navigator}>
// 右側按鈕為圖標
<NavigatorBar name="我的" navigator={this.props.navigator} rightButton={{onPress: () => this.props.navigator.push({component: Setting}), icon: require('../../assets/icon-set.png')}} />
// 右側按鈕為文字
<NavigatorBar name="我的訂單" navigator={this.props.navigator} rightButton={{text: '設置', onPress: () => this.props.navigator.push({component: OrderHitory})}} />

圖片輪播

建議使用第三方的 react-native-viewpager 元件,安裝方式請查閱官方文件。下面是一個 Demo:

var ViewPager = require('react-native-viewpager');
<ViewPager
  animation={(animatedValue, toValue, ...) => {
    var velocity = Math.abs(gestureState.vx);
    var baseDuration = 300;
    var duration = (velocity > 1) ? 1/velocity * baseDuration : baseDuration;
    return Animated.timing(animatedValue, {
      toValue: toValue, duration: duration, easing: Easing.out(Easing.exp)
    });
  }}
  datasource={this.state.dataSource}
  renderPage={this._renderPage} />
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved