我正在为我的应用设置基本的身份验证屏幕。
我现在正在做的是一个调用名为auth
的函数的按钮。
我的问题是,当我单击按钮,依次调用该函数时,我的函数中似乎没有执行任何操作。
这是我的代码:
import React from "react";
import {
View,
TextInput,
StyleSheet,
Alert,
KeyboardAvoidingView,
Dimensions
} from "react-native";
import { Button, Text } from "native-base";
let width = Dimensions.get("window").width;
let height = Dimensions.get("window").height;
export default class Login extends React.Component {
static navigationOptions = {
title: "Login to Aeries"
};
constructor(props) {
super(props);
this.state = { isAuthed: false, username: "", authError: false, password: "" };
this.auth = this.auth.bind(this);
const showAlert = () => {
Alert.alert(
'There was an error loging in. Please check your username and password and try again.'
)
}
}
auth(){
//do auth
this.setState({ authError: false,isAuthed: false });
if (this.state.isAuthed === false && this.state.isAuthed === false && this.state.username == "admin" && this.state.password == "admin") { // authentication is successful
this.setState({ isAuthed: true });
this.props.navigation.navigate("Grades")
} else { // auth error
this.setState({ authError: true,isAuthed: false });
this.showAlert
}
};
render() {
const { showAlert } = this.state
return (
<View style={styles.wrapper}>
<KeyboardAvoidingView behavior="padding" style={styles.loginContainer}>
<TextInput
placeholder="school email"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
placeholderTextColor="white"
style={styles.input}
value={this.state.username}
/>
<TextInput
placeholder="password"
secureTextEntry
autoCorrect={false}
autoCapitalize="none"
placeholderTextColor="white"
style={styles.input}
value={this.state.password}
/>
<View style={{
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
margin: 12
}}>
<Button
primary
onPress={this.auth}
>
<Text> Login </Text>
</Button>
</View>
</KeyboardAvoidingView>
</View>
);
}
}
const styles = {
loginContainer: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: width - 42,
backgroundColor: "#bdc3c7",
borderRadius: 9,
marginTop: 21,
marginBottom: 21
},
input: {
paddingHorizontal: 10,
color: "#2c3e50",
backgroundColor: "#95a5a6",
margin: 12,
height: 42,
width: width - 69,
borderRadius: 3
},
logo: {
width: 231,
height: 231
},
wrapper: {
flex: 1,
alignItems: "center",
justifyContent: "center",
marginTop: -21
},
loginButton: {
borderRadius: 3,
marginTop: 9,
marginBottom: 21
},
error: {
color: 'red',
textAlign: 'center',
}
};
当我单击按钮时应该发生什么,因为它应该调用auth
函数
auth函数应检查用户名和密码是否均为admin
,如果是,则导航至名为Grades
的屏幕
(顺便说一句,我正在使用反应导航)
如果用户名和密码不是“ admin”,则应显示一条警报,提示身份验证不成功。
先谢谢了。让我知道您是否想要附加任何其他代码。
答案 0 :(得分:0)
您的方法是错误的
在构造函数中绑定函数
constructor(props) {
super(props);
this.auth = this.auth.bind(this);
}
设置这样的功能
auth() {
// Your chunk of code
}
按钮应该是这样
<Button onPress={this.auth} />
如果有任何问题,请在评论部分告诉我!
选中此live demo