React Native联系人组件

本文原创首发于公众号:ReactNative开发圈,转载需注明出处。

React Native通讯录联系人组件,名叫:react-native-contacts,可以用来增加、读取、修改、删除、搜索手机通讯录中的联系人信息,兼容IOS和安卓双平台。

安装

npm install react-native-contacts
react-native link react-native-contacts

iOS权限配置

需要增加读取联系人的权限,在Info.plist中增加一个key:"Privacy - Contacts Usage Description”。


React Native联系人组件_第1张图片
image.png

Android权限配置

在android/app/src/main/AndroidManifest.xml中增加以下权限:


  
  

支持的方法

React Native联系人组件_第2张图片
image.png

示例

增加联系人

var newPerson = {
  emailAddresses: [{
    label: "work",
    email: "[email protected]",
  }],
  familyName: "Nietzsche",
  givenName: "Friedrich",
}

Contacts.addContact(newPerson, (err) => { /*...*/ })

更新和删除联系人

Contacts.getAll( (err, contacts) => {
  //update the first record
  let someRecord = contacts[0]
  someRecord.emailAddresses.push({
    label: "junk",
    email: "[email protected]",
  })
  Contacts.updateContact(someRecord, (err) => { /*...*/ })

  //delete the second record
  Contacts.deleteContact(contacts[1], (err) => { /*...*/ })
})

获取所有联系人

var Contacts = require('react-native-contacts')

Contacts.getAll((err, contacts) => {
  if(err === 'denied'){
    // error
  } else {
    // contacts returned in []
  }
})

如果联系人比较多的话,getAll方法会比较慢,作者建议先获取好所有联系人,存储在本地数据库中。在需要用的时候,直接读取本地数据库,这样速度比较快。

搜索联系人

var Contacts = require('react-native-contacts')

Contacts.getContactsMatchingString("filter", (err, contacts) => {
  if(err === 'denied'){
    // x.x
  } else {
    // Contains only contacts matching "filter"
    console.log(contacts)
  }
})

组件地址

详细的源码和使用说明请访问GitHub:https://github.com/rt2zz/react-native-contacts

举手之劳关注我的微信公众号:ReactNative开发圈

React Native联系人组件_第3张图片
image.png

你可能感兴趣的:(React Native联系人组件)