登录
import React, { Component } from "react";
import { Alert, View, AsyncStorage, TextInput, Button } from "react-native";
export default class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
psw: ""
};
}
onChangeName = text => {
this.setState({ name: text });
};
onChangePsw = text => {
this.setState({ psw: text });
};
login = async () => {
if (this.state.name != null && this.state.name != "") {
if (this.state.psw != null && this.state.psw != "") {
await AsyncStorage.setItem("name", this.state.name);
await AsyncStorage.setItem("psw", this.state.psw);
this.props.navigation.navigate("Home");
} else {
Alert.alert("密码不能为空");
}
} else {
Alert.alert("帐号不能为空");
}
};
render() {
return (
<View style={{ flex: 1 }}>
<TextInput
placeholder="请输入帐号..."
onChangeText={this.onChangeName}
/>
<TextInput
placeholder="请输入密码..."
onChangeText={this.onChangePsw}
/>
<Button title="登录" onPress={this.login} />
</View>
);
}
}
判断有没有存入本地
import React, { Component } from "react";
import { View, AsyncStorage, Text } from "react-native";
import {
StackNavigator,
createSwitchNavigator,
createTabNavigator,
createBottomTabNavigator
} from "react-navigation";
import HomePage from "./HomePage";
import LoginPage from "./LoginPage";
class AuthPage extends Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
const name = await AsyncStorage.getItem("name");
const psw = await AsyncStorage.getItem("psw");
if (name !== null && name != "" && psw != null && psw != "") {
this.props.navigation.navigate("Home");
} else {
this.props.navigation.navigate("Login");
}
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>qqqqqqq</Text>
</View>
);
}
}
const Switch = createSwitchNavigator({
Auth: { screen: AuthPage },
Home: { screen: HomePage },
Login: { screen: LoginPage }
});
export default Switch;
注销
import React, { Component } from "react";
import { View, Text, Button, AsyncStorage } from "react-native";
export default class HomePage extends Component {
onClick = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate("Login");
};
render() {
return (
<View style={{ flex: 1 }}>
<Text style={{ textAlign: "center" }}>hello</Text>
<Button title="注销" onPress={this.onClick} />
</View>
);
}
}