React Native:onPress 不适用于身份验证

时间:2021-06-12 18:02:34

标签: javascript react-native

我正在从 React 过渡到 React Native,到目前为止已经掌握了基础知识。在我的应用程序中,我正在尝试实施身份验证。

我已经为登录和注册设置了可用的 API,并使用 POSTMAN 对其进行了验证。

这里的问题是出于某种原因 onPress={onSignInHandler} 没有做任何事情。通常在 React 中,我会输入 onClick={onSignInHandler},一切都会正常工作。

我想,当按下 Login 时,执行 axios 请求,然后重定向到例如“Myprofil.js”组件或至少显示和警报以查看它是否正常工作。 据我所知,React Native 使用 react-navigation 而不是 react-router

app.js:

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Login from './src/views/Login';
import Signup  from './src/views/Signup ';
import MyProfil from './src/views/MyProfil';
 

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login" screenOptions={{
    headerShown: false
  }}>
        <Stack.Screen name="Login" component={Login} /> 
        <Stack.Screen name="Signup " component={Signup} />
       <Stack.Screen name="MyProfil" component={MyProfil} />
      </Stack.Navigator> 
    </NavigationContainer>
  );
}

export default App;

登录.js:

import React, { Component, UseState } from 'react';
import { View, Text, TextInput, StyleSheet, Image, Dimensions, Alert } from 'react-native';
import axios from "axios";

const { width, height } = Dimensions.get('window');  

function Login() {

    const [state, setState] = React.useState({
        msg: "",
        isLoading: false,
        redirect: false,
        errMsgEmail: "",
        errMsgPwd: "",
        errMsg: "",
    });

    const [email, setEmail] = React.useState(""); 
    const [password, setPassword] = React.useState(""); 
 

     const handleChangeEmail = (event) => {
      setEmail(event.target.value);
     };

    const handleChangePassword = (event) => {
        setPassword(event.target.value);
    };

    function onSignInHandler() {
      const infos = {
        email: email,
        password: password,
    };
      axios
      .post("http://127.0.0.1:8000/api/login", infos)
        .then((response) => {
          if (response.data.status === 200) {
              localStorage.setItem("isLoggedIn", true);
              localStorage.setItem("userData", JSON.stringify(response.data.data));
            this.setState({
              msg: response.data.message,
              redirect: true,
            });      
          }
          if (
            response.data.status === "failed" &&
            response.data.success === undefined
          ) {
            this.setState({
              errMsgEmail: response.data.validation_error.email,
              errMsgPwd: response.data.validation_error.password,
            });
            setTimeout(() => {
              this.setState({ errMsgEmail: "", errMsgPwd: "" });
            }, 2000);
          } else if (
            response.data.status === "failed" &&
            response.data.success === false
          ) {
            this.setState({
              errMsg: response.data.message,
            });
            setTimeout(() => {
              this.setState({ errMsg: "" });
            }, 2000);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    };

    return (
        <View
          style={{
            flex: 1,
            backgroundColor: 'white',
            justifyContent: 'flex-end'
          }}
        >

          <View style={{ ...StyleSheet.absoluteFill }}>

            <Image
              source={require('../images/bg.jpg')}
              style={{ flex: 1, height: null, width: null }}
            > 
            </Image>

          </View>
          <View style={{ height: height / 2, justifyContent: 'center' }}>
          <View>
              <Text style={{ fontSize: 20, fontWeight: 'bold', color:"#ffffff",fontSize: 30, marginHorizontal: 40,marginVertical: 10, }}>Bienvenue !</Text> 
            </View>
            <View style={styles.button}>
              <TextInput placeholder="E-mail " style={{ fontSize: 20, fontWeight: 'bold' }} value={email} onChange={handleChangeEmail}></TextInput>
            </View>

            <View style={styles.button}>
              <TextInput placeholder="Password" style={{ fontSize: 20, fontWeight: 'bold' }} secureTextEntry={true}  value={password} onChange={handleChangePassword}></TextInput>
            </View>

            <View style={{alignItems: 'center',justifyContent: 'center',  marginTop: 20}}>
              <Text style={{ fontSize: 20, fontWeight: 'bold', color: '#ffffff' }} onPress={onSignInHandler}>
                LOGIN
              </Text>
            </View>
            
          </View>

        </View>

      );
  }

export default Login;


const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    button: {
      backgroundColor: 'white',
      height: 50,
      marginHorizontal: 30,
      borderRadius: 35,
      alignItems: 'center',
      justifyContent: 'center',
      marginVertical: 10,
    }
  });

2 个答案:

答案 0 :(得分:1)

不要使用 onPress for Text 组件,而是使用 TouchableOpacity 将其包装起来,并使用 TouchableOpacity 的 onPress

<TouchableOpacity onPress={onSignInHandler}>
<Text style={{ fontSize: 20, fontWeight: 'bold', color: '#ffffff' }} title="Profil" >LOGIN</Text>
</TouchableOpacity>

答案 1 :(得分:0)

改变你的

function onSignInHandler() {

const onSignInHandler = () => {