本文原創(chuàng)首發(fā)于公眾號(hào):ReactNative開發(fā)圈,轉(zhuǎn)載需注明出處。
React Native通訊錄聯(lián)系人組件,名叫:react-native-contacts,可以用來增加、讀取、修改、刪除、搜索手機(jī)通訊錄中的聯(lián)系人信息,兼容IOS和安卓雙平臺(tái)。
安裝
npm install react-native-contacts
react-native link react-native-contacts
iOS權(quán)限配置
需要增加讀取聯(lián)系人的權(quán)限,在Info.plist中增加一個(gè)key:"Privacy - Contacts Usage Description”。

image.png
Android權(quán)限配置
在android/app/src/main/AndroidManifest.xml中增加以下權(quán)限:
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
支持的方法

image.png
示例
增加聯(lián)系人
var newPerson = {
emailAddresses: [{
label: "work",
email: "mrniet@example.com",
}],
familyName: "Nietzsche",
givenName: "Friedrich",
}
Contacts.addContact(newPerson, (err) => { /*...*/ })
更新和刪除聯(lián)系人
Contacts.getAll( (err, contacts) => {
//update the first record
let someRecord = contacts[0]
someRecord.emailAddresses.push({
label: "junk",
email: "mrniet+junkmail@test.com",
})
Contacts.updateContact(someRecord, (err) => { /*...*/ })
//delete the second record
Contacts.deleteContact(contacts[1], (err) => { /*...*/ })
})
獲取所有聯(lián)系人
var Contacts = require('react-native-contacts')
Contacts.getAll((err, contacts) => {
if(err === 'denied'){
// error
} else {
// contacts returned in []
}
})
如果聯(lián)系人比較多的話,getAll方法會(huì)比較慢,作者建議先獲取好所有聯(lián)系人,存儲(chǔ)在本地?cái)?shù)據(jù)庫中。在需要用的時(shí)候,直接讀取本地?cái)?shù)據(jù)庫,這樣速度比較快。
搜索聯(lián)系人
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)
}
})
組件地址
詳細(xì)的源碼和使用說明請(qǐng)?jiān)L問GitHub:https://github.com/rt2zz/react-native-contacts
舉手之勞關(guān)注我的微信公眾號(hào):ReactNative開發(fā)圈

image.png