API 組件

使用 API 前,都要導入相對應的物件。

API(Application Programming Interface),是功能面的組件,用於與原生平台溝通的函數。

基礎 API

  • StyleSheet:

    建立樣式

  • AppState:

    • 可取得應用的狀態

      • active:前台運行

      • background:後台運行

      • inactive:前後台切換過程中

    • 可自訂事件監聽

  • NetInfo:

    • 獲取網路狀態的 API

    • 使用時只需調用 getConnectionInfo() 即可獲得網路狀態

      • none:離線

      • wifi

      • cellular

      • unknown

      • buetooth

      • ethernet

      • wimax

      可自訂事件監聽

    • 可用於判斷目前流量是否收費

平台 API

  • Platform:

    • 不同平台的樣式設定可能不同,用於判斷平台進行修正。

  • BackHandler

    • 用於監聽 Android 返回鍵的 API

    improt {Platform,BackHandler} from react native
    
    componentDidMount() {
        if (Platform.OS === 'android'){
          BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
      }
    
     componentWillUnmount() {
        if (Platform.OS === 'android') {
          BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
      }
    
      onBackAndroid = () => {
        //禁用返回键
        if(this.props.navigation.isFocused()) {//判断   该页面是否处于聚焦状态
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
              //最近2秒内按过back键,可以退出应用。
              // return false;
              BackHandler.exitApp();//直接退出APP
            }else{
              this.lastBackPressed = Date.now();
              ToastAndroid.show('再按一次退出应用', 1000);//提示
              return true;
            }
        }
      }
  • PermissionsAndroid

    • 用於 Android 6.0 以上的動態權限問題。若是被列為危險權限,需動態取得使用者授權才能使用。例:月曆、相機、聯絡人、位置、麥克風、電話、SENSORS、簡訊、記憶卡…

    • 若要一次申請多個動態權限,可使用PermissionsAndroid.requestMultiple(permisions) 方法。 參數 permissions 是要申請的權限陣列。

    // 要先在 AndroidManifest.xml 加入需要申請的動態權限
    // 例如申請相機權限
    <uses-permission android:name="android.permission.CAMERA" />
    
    
    // 動態申請邏輯
    import React from "react";
    import { StyleSheet, Text, View, SafeAreaView, PermissionsAndroid, Button } from "react-native";
    import Constants from "expo-constants";
    
    const requestCameraPermission = async () => {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: "申請相機權限",
            message:
              "需要提供相機權限",
            buttonNeutral: "Ask Me Later",
            buttonNegative: "Cancel",
            buttonPositive: "OK"
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("取得相機權限");
        } else {
          console.log("被拒絕取得權限");
        }
      } catch (err) {
        console.warn(err);
      }
    };

螢幕相關 API

  • Dimensions:

    • 取螢幕尺寸

    • 用Dimensions.get('windows').width 取組件寬度

  • PixelRatio:

    • 取螢幕像素密度

    • 在 React Native 開發中,使用的尺寸單位是 pt,但由於移動設備的解析度不一樣,即 1pt 對應的像素個數是不一樣的。為此,React Native 提供了 PixelRatio API 來告知開發者當前設備的像素密度。使用 PixelRatio.get() 可取得像素密度,是1以上的數值。

    • 在開發中,為了保證圖片在不同的設備上顯示的效果保持一致,往往需要準備多套圖片,比如iOS開發中的@1x,@2x,@3x圖。在RN中通過圖元密度來獲取圖片在不同設備上需要的真正大小。

import {Component} from 'react';
import {Image, PixelRatio} from 'react-native';
 
export default class MyUserThumbnail extends Component {
 
    render() {
      const width = PixelRatio.getPixelSizeForLayoutSize(200)
      const height = PixelRatio.getPixelSizeForLayoutSize(100)
 
      return <View>
                <Image source={{uri: 'http://some-uri.com/uri', 
                  width: width, height: height }} 
                  style={{width: 202, height: 100}}/>;
             </View>
    }
}

使用者位置取得

  • 皆要取得許可權才可使用

  • ios在Info.plist檔案加入NSLocationWhenInUseUsageDescription欄位(若用react-native init 指令建立專案已自動增加)

  • android 在AndroidManifest.xml 加入

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
import React, { Component } from 'react';
import {Button,View } from 'react-native';

var Geolocation = require('Geolocation');

export default class GeolocationDemo extends Component{
    render(){
        return(
            <View>
                <Button title="Geolocation" onPress={()=>{
                    Geolocation.getCurrentPosition(
                    //1.定位資訊
                    (location)=>{
                        console.log(location);
                    },
                    //2.失敗回呼
                    ()=>{
                        console.log("error");
                    },{
                    //3.設定參數
                        //定位逾時,毫秒
                        timeout:2000,
                        //有效期,毫秒
                        maximumAge:100000,
                    });
                }}/>
            </View>
        );
    };
}

呼叫裝置震動模組

android 在AndroidManifest.xml 加入

<uses-permission android:name="android.permission.VIBRATE" />
render(){
    return(
        <View>
            <Button title="NetInfo" 

            onPress={()=>{
            //陣列奇數個數的值:震動時間
            //陣列偶數個數的值:停頓時間
            //布林值:是否循環震動
            Vibration.vibrate([1000,3000,2000,1000],false);
            }}/>
        </View>
    );
}

Last updated