推荐使用React Native FBSDK:社区驱动的Facebook SDK集成方案
import React from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import {
LoginButton,
AccessToken,
GraphRequest,
GraphRequestManager
} from 'react-native-fbsdk';
export default class LoginScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
userInfo: null
};
}
componentDidMount() {
AccessToken.getCurrentAccessToken().then(
(data) => {
if (data) {
this._fetchUserInfo();
}
}
);
}
_fetchUserInfo() {
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback
);
new GraphRequestManager().addRequest(infoRequest).start();
}
_responseInfoCallback = (error, result) => {
if (error) {
console.log('Error fetching data: ', error);
} else {
this.setState({
userInfo: result
});
}
};
render() {
return (
<View style={styles.container}>
<LoginButton
readPermissions={['public_profile', 'email']}
onLoginFinished={
(error, result) => {
if (error) {
console.log('Login failed with error: ' + error.message);
} else if (result.isCancelled) {
console.log('Login was cancelled');
} else {
console.log('Login was successful with permissions: ' + result.grantedPermissions);
this._fetchUserInfo();
}
}
}
/>
<Text style={styles.welcome}>
{this.state.userInfo ? JSON.stringify(this.state.userInfo) : 'No user info'}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
welcome: {
margin: 10,
textAlign: 'center',
color: '#333333',
},
});
这段代码展示了如何在React Native应用中集成和使用Facebook SDK来实现用户登录,并获取用户的基本信息。代码使用了react-native-fbsdk
库中的LoginButton
和GraphRequest
来简化登录流程和用户信息的获取。同时,它提供了一个简洁的用户界面来显示登录状态和用户信息。
评论已关闭