React Native API

AppRegistry

AppRegistry是JS运行所有React Native应用的入口。

最常用的是:注册根组件
registerComponent(appKey, getComponentFunc)

1
AppRegistry.registerComponent('Test', () => SampleComponent);

AsyncStorage

异步存储读取

(第三方的)react-native-storage

AlertIOS

  1. static alert(title, message?, callbackOrButtons?)

    • callbackOrButtons:一个函数func(()=> void)或者button数组 ButtonsArray
      • 默认情况下,CancelOK, func是点OK的方法
    • ButtonsArray: 对象数组,有以下几个参数

      • text:
      • onPress:
      • style: AlertButtonStyle
        • default
        • cancel
        • destructive
      1
      2
      3
      4
      5
      6
      7
      8
      9
      this.customButtons = [{
      text: 'Custom OK',
      onPress: this.saveResponse(按钮方法)
      },
      {
      text: 'Custom cancel',
      style: 'cancel',(default/cancel/destructive)
      }
      ];
  2. static prompt(title, message?, callbackOrButtons?, type?, defaultValue?) 有输入框的提示,可以用于提示用户名/密码输入

    • type: AlertType

      • default
      • plain-text
      • secure-text
      • login-password
      1
      2
      3
      4
      5
      6
      AlertIOS.prompt(
      'input your password',
      null,
      this.customButtons,
      'login-password',
      'userName')

ActionSheetIOS

  1. static showActionSheetWithOptions(options, callback)

    • options 字符串数组,button title
    • cancelButtonIndex
    • destructiveButtonIndex
    • title
    • message
    • tintColor
    • callBack 回调func,

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      showActionSheet = ()=> {
      ActionSheetIOS.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: CANCEL_INDEX,
      destructiveButtonIndex: DESTRUCTIVE_INDEX,
      tintColor: 'green',
      title: 'action sheet title',
      message: 'message'
      },
      (buttonIndex) => {
      this.setState({clicked: BUTTONS[buttonIndex]});
      });
      };
  2. static showShareActionSheetWithOptions(options, failureCallback, successCallback) 分享弹出框

    • url
    • message
    • subject 主题
    • excludedActivityTypes 弹出框中不显示的活动

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      showShareActionSheet = ()=> {
      UIManager.takeSnapshot('window').then((uri)=> {
      ActionSheetIOS.showShareActionSheetWithOptions({
      url: uri,
      message: 'message to go with shared url',
      subject: 'a subject to go in the email heading',
      excludedActivityTypes: [
      'com.baidu.www'
      ]
      },
      (error) => alert(error),
      (success, method) => {
      var text;
      if (success) {
      text = 'Shared via ${method}';
      } else {
      text = 'You didn\'t share';
      }
      this.setState({text});
      });
      }).catch((error) => alert(error));
      }

PixelRatio

相当于iOS中的[UIScreen mainScreen].scale

  1. static get()

    • PixelRatio.get() === 1
      • mdpi Android devices (160 dpi)
    • PixelRatio.get() === 1.5
      • hdpi Android devices (240 dpi)
    • PixelRatio.get() === 2
      • iPhone 4, 4S
      • iPhone 5, 5c, 5s
      • iPhone 6
      • xhdpi Android devices (320 dpi)
    • PixelRatio.get() === 3
      • iPhone 6 plus
      • xxhdpi Android devices (480 dpi)
    • PixelRatio.get() === 3.5
      • Nexus 6
  2. static getPixelSizeForLayoutSize(layoutSize)
    将布局尺寸,转化为像素尺寸。返回的是整数数值

    1
    2
    3
    4
    5
    var image = getImage({
    width: PixelRatio.getPixelSizeForLayoutSize(200),
    height: PixelRatio.getPixelSizeForLayoutSize(100),
    });
    <Image source={image} style={{width: 200, height: 100}} />

AppState

常用于推送通知

  1. currentState 当前状态
  2. addEventListener(type, handler) 添加事件监听
  3. removeEventListener(type, handler)移除事件监听

NetInfo

获取网络状态和类型,用时再查找

CameralRoll

提供相册相关的功能

  • static saveToCameraRoll(tag, type?) 存储

    • type: 只能是photo 或者video

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      CameraRoll.saveToCameraRoll(imgURL + img1, 'photo')
      .then((url)=>{
      console.log('-----' + url);
      var photos =_that.state.photos;
      photos.unshift(url);
      _that.setState({
      photos: photos
      });
      AlertIOS.alert('图片1保存成功');
      })
      .catch((error)=> {
      AlertIOS.alert('图片1保存失败' + error);
      })
  • static getPhotos(params) 获取图片

  • react-native-camera

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    var fetchParams ={
    first: 4,
    groupTypes: 'All',
    assetType: 'Photos',
    };
    var imgURL = 'http://vczero.github.io/lvtu/img/';
    componentDidMount() {
    var _that = this;
    CameraRoll.getPhotos(fetchParams)
    .then((data)=> {
    console.log('====' + data.edges);
    var edges = data.edges;
    var photos = [];
    for (var i in edges){
    photos.push(edges[i].node.image.uri);
    }
    _that.setState({
    photos: photos
    });
    }, ()=> {
    alert('图片获取失败');
    });
    }

Vibration

控制设备震动

Geolocation

处理位置信息

  1. iOS
    • plist 添加NSLocationWhenInUseUsageDescription字段
    • 使用react-native init创建的项目,默认开启定位功能
  2. Android

    • AndroidManifest.xml 添加<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  3. static getCurrentPosition(geo_success, geo_error?, geo_options?) 获取当前位置信息

    • geo_options
      • enableHighAccuracy : bool, 是否高精度
      • timeout 超时时间
      • maximumAge 多久之后再次获取,即重复获取时间间隔
  4. static watchPosition(success, error?, options?) 监听位置变换信息
  5. static clearWatch(watchID)
  6. static stopObserving()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
this.watchID = navigator.geolocation.watchPosition((position) => {
var lastPosition = JSON.stringify(position);
this.setState({lastPosition});
});
}

数据请求

fetch封装程度更好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
_postRequest(url, data, callback) {
var opt = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
};
fetch(url, opt)
.then((response) => response.json())
.then((responseJson)=>{
console.log(responseJson);
callback(responseJson);
})
.catch((error)=>{
console.warn(error);
});
}