推荐开源项目:React Native Contacts - 管理手机通讯录的完美解决方案
import React from 'react';
import { View, Text, Button, PermissionsAndroid } from 'react-native';
import Contacts from 'react-native-contacts';
export default class ContactsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
contacts: [],
};
}
componentDidMount() {
this.requestContactsPermission();
}
requestContactsPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: 'Contacts Permission',
message: 'This app needs access to your contacts ' +
'so you can save them into your app.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.fetchContacts();
} else {
console.log('Contacts permission denied');
}
} catch (err) {
console.warn(err);
}
}
fetchContacts = () => {
Contacts.getAll().then(contacts => {
this.setState({ contacts });
});
}
render() {
return (
<View>
<Button title="Fetch Contacts" onPress={this.fetchContacts} />
{this.state.contacts.map(contact => (
<View key={contact.recordID}>
<Text>{contact.givenName}</Text>
<Text>{contact.familyName}</Text>
</View>
))}
</View>
);
}
}
这段代码示例展示了如何在React Native应用中请求通讯录权限,获取并展示通讯录联系人列表。它使用了react-native-contacts
库来处理通讯录相关操作,并结合了React Native的组件和生命周期方法。
评论已关闭