Вызов функции аутентификации в реагирующем - PullRequest
0 голосов
/ 24 июня 2018

Я настраиваю базовый экран аутентификации для своего приложения.
То, что у меня сейчас происходит, - это кнопка, вызывающая функцию с именем 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

Функция аутентификации должна проверять, являются ли имя пользователя и пароль admin, и, если это так, перейти к экрану с именем Grades (кстати, я использую реагирующую навигацию)

Если имя пользователя ипароль не 'admin', тогда должно появиться предупреждение о том, что аутентификация не удалась.

Заранее спасибо.Дайте мне знать, если вы хотите, чтобы я добавил другой код.

1 Ответ

0 голосов
/ 24 июня 2018

Ваш подход неверен, сделайте это

Привязать функцию в конструкторе

constructor(props) {
   super(props);
   this.auth = this.auth.bind(this);
}

установить функцию следующим образом

auth() {
   // Your chunk of code
}

Кнопка должна быть такой

<Button onPress={this.auth} />

Если есть какие-либо проблемы, дайте мне знать в разделе комментариев!

Проверьте это live demo

...