import React from 'react';
import { View, Text, Button } from 'react-native';
import { SimpleAuth } from 'react-native-simple-auth';
export default class AuthScreen extends React.Component {
constructor(props) {
super(props);
this.auth = new SimpleAuth();
this.state = {
userInfo: null,
};
}
componentDidMount() {
this.auth.on('login', userInfo => {
this.setState({ userInfo });
});
}
loginWithFacebook = async () => {
try {
const userInfo = await this.auth.loginWithFacebook();
this.setState({ userInfo });
} catch (error) {
console.error('Login failed with Facebook', error);
}
};
logout = async () => {
try {
await this.auth.logout();
this.setState({ userInfo: null });
} catch (error) {
console.error('Logout failed', error);
}
};
render() {
const { userInfo } = this.state;
return (
<View>
{userInfo ? (
<Text>Welcome, {userInfo.name}!</Text>
) : (
<Text>Please login to continue.</Text>
)}
<Button title="Login with Facebook" onPress={this.loginWithFacebook} />
{userInfo && <Button title="Logout" onPress={this.logout} />}
</View>
);
}
}
这个代码示例展示了如何在React Native应用中使用react-native-simple-auth
库来实现Facebook登录。SimpleAuth
实例监听登录事件,并在用户登录时更新状态。同时,它提供了一个登录和注销的方法。这个例子简洁地展示了如何将认证功能整合到React Native应用中。