You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native点击按钮无法触发Save函数的问题求助

登录表单Save函数无法执行问题求助

我用Formik+Yup做登录表单验证,通过Axios写了Save函数向Node.js API发送POST请求,但遇到以下问题:

  • 点击提交按钮时Save函数完全不运行
  • 单独用console.log(values)能正常获取所有表单值,但调用Save(values)无任何反应
  • 按照Formik文档设置按钮onPress={handleSubmit}也无效

以下是我的代码:

import React from 'react';
import { View, Image, Text, TouchableOpacity, TextInput, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import * as Yup from 'yup';
import { Formik } from 'formik'
import Background from './../../components/Background';
import { API } from "./../../config/config";
import Btn from './../../components/Btn';

const LoginSchema = Yup.object().shape({
    email: Yup.string()
        .min(6, "Demasiado corto")
        .max(100, "Demasiado largo")
        .email("No corresponde a un email válido.")
        .required("Requerido"),
    pwd: Yup.string()
        .min(8, "Demasiado corto")
        .max(100, "Demasiado largo")
        .required("Requerido"),
});

const Login = (props) => {

    const loginform = {
        email: '',
        pwd: ''
    }

    const Save = (value) => {
        console.log(value);
        axios({
            method: 'post',
            url: `${API}/login`,
            data: {
                email: value.email,
                pwd: value.pwd
            },
        }).then((response) => {
            let data = response.data;
            if (data.OK === true) {
                alert("Bienvenido " + data.User.Usuario[0].NombreCompleto);
                props.navigation.navigate("Home")
                AsyncStorage.setItem(
                    'TOKEN',
                    data.TOKEN,
                );
            } else {
                if (data.OK === false) {
                    Alert(data.message, 2)
                }
            }
        }).catch((e) => {
            let error = e.message;
            if (error.OK === false) {
                alert(error.message)
            }
        })
    }

    return (
        <Background>
            <View style={{ alignItems: 'center', width: 460 }}>
                <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', marginRight: 50, marginTop: 100 }}>
                    <Image source={require('./../../assets/Logo.png')} />
                </View>
                <View
                    style={{
                        felx: 1,
                        height: 700,
                        width: '100%',
                        paddingTop: 40,
                        marginRight: 50,
                        alignItems: 'center',
                    }}>
                    <Formik
                        initialValues={loginform}
                        validationSchema={LoginSchema}
                        onSubmit={values => console.log(values) }
                    >
                        {({ handleChange, handleBlur, handleSubmit, values, errors, touched, isValid, }) => (
                            <View>
                                <TextInput
                                    name="email"
                                    placeholder="Email"
                                    onChangeText={handleChange('email')}
                                    onBlur={handleBlur('email')}
                                    value={values.email}
                                    keyboardType="email-address"
                                    style={{ paddingHorizontal: 30, backgroundColor: 'white', marginVertical: 10, width: '60%' }}
                                    placeholderTextColor='gray'>
                                </TextInput>
                                {(errors.email && touched.email) &&
                                    <Text style={{ fontSize: 10, color: 'red' }}>{errors.email}</Text>
                                }
                                <TextInput
                                    name="pwd"
                                    placeholder="Contraseña"
                                    onChangeText={handleChange('pwd')}
                                    onBlur={handleBlur('pwd')}
                                    value={values.pwd}
                                    secureTextEntry={true}
                                    style={{ paddingHorizontal: 30, backgroundColor: 'white', marginVertical: 10, width: '60%' }}
                                    placeholderTextColor='gray'>
                                </TextInput>
                                {(errors.pwd && touched.pwd) &&
                                    <Text style={{ fontSize: 10, color: 'red' }}>{errors.pwd}</Text>
                                }
                                <View
                                    style={{ alignItems: 'flex-start', width: '60%', paddingRight: 10, marginBottom: 10 }}>
                                    <TouchableOpacity onPress={() => props.navigation.navigate("RecuperarPWD")}>
                                        <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>
                                            ¿Olvidó su contraseña?
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                                <Button style={{ color: 'white', width: 200, backgroundColor: '#FF8029'}} onPress={handleSubmit} title="Iniciar Sesión" disabled={!isValid}/>
                            </View>
                        )}
                    </Formik>
                    <View style={{ display: 'flex', flexDirection: 'row', justifyContent: "center" }}>
                        <Btn textColor='white' width={365} bgColor='#FF8029' mt={120} mr={15} btnLabel="¿Aún no tienes una cuenta? ¡Registrate!" Press={() => props.navigation.navigate("Registro")} />
                    </View>
                </View>
            </View>
        </Background>
    );
};

export default Login;

核心问题与修复方案

  1. Formik未关联Save函数
    原代码中Formik的onSubmit仅打印表单值,未调用Save函数。修改Formik配置:

    <Formik
        initialValues={loginform}
        validationSchema={LoginSchema}
        onSubmit={Save} // 将Save绑定到onSubmit
    >
    
  2. Alert组件未导入
    代码中使用了Alert但未从react-native导入,会导致运行时错误阻塞执行。补充导入:

    import { View, Image, Text, TouchableOpacity, TextInput, Button, Alert } from 'react-native';
    
  3. Alert调用方式错误
    React Native的Alert需使用标准调用格式,替换原错误写法:

    // 原代码:Alert(data.message, 2)
    Alert.alert("登录失败", data.message);
    
  4. Catch块错误处理逻辑错误
    e.message是字符串类型,无法访问error.OK,调整错误处理:

    .catch((e) => {
        console.error("登录请求错误:", e);
        alert("请求失败,请检查网络或稍后重试");
    })
    
  5. 布局拼写错误
    View样式中的felx:1是拼写错误,改为flex:1,避免布局异常导致按钮不可点击。

内容的提问来源于stack exchange,提问作者Ronald Correa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:47:06