簡體   English   中英

在 React 中禁用表單提交上的按鈕

[英]Disable button on Form Submit in React

出於某種原因,提交表單時,我的登錄按鈕不會被禁用。 有什么明顯不正確的嗎?

它應該在處理用戶的登錄 API 請求時被禁用。

這也不是快速 API 的結果,因為即使我將網絡速度設置為非常慢,它也不會在任何時候被禁用。

import React, { useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Alert, Box, Card, TextField, Typography,
} from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton';
import { useAuth } from '../context/AuthContext';
import '../../pages/bg.css';

export default function SignInAuth() {
  const emailRef = useRef();
  const passwordRef = useRef();
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const auth = useAuth();

  async function handleSubmit(e) {
    e.preventDefault();

    if (!emailRef.current.value) {
      return setError('Please enter an Email Address');
    }

    if (!passwordRef.current.value) {
      return setError('Please enter a password');
    }

    setLoading(true);
    setError('');

    fetch(
      `${process.env.REACT_APP_API_URL}auth/login`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          Email: emailRef.current.value,
          Password: passwordRef.current.value,
        }),
      },
    ).then((response) => {
      if (response.ok) {
        auth.signin(emailRef.current.value);
        return navigate('/Dashboard');
      }
      // Response must be handled in a promise.
      return response.json().then((errorText) => { throw new Error(errorText.message); });
    }).then(setLoading(false)).catch((err) => {
      setError(err.message); // This comes from the returned error promise.
      // System throws error, and then error is set for the text.
    });
    return null;
  }

  const onSubmit = (e) => {
    handleSubmit(e);
  };

  const textFieldStyle = {
    width: '300px',
  };

  return (
    <Box sx={{
      zIndex: 1,
      minWidth: '200px',
      width: '450px',
    }}
    >
      <Card sx={{ p: '20px', borderRadius: '15px' }}>
        <Typography variant="h4" sx={{ fontWeight: 600, textAlign: 'center', mb: '8px' }}>Sign In</Typography>

        <form onSubmit={(e) => onSubmit(e)}>
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            {error && <Alert severity="error" sx={{ ...textFieldStyle, my: '10px' }}>{error}</Alert>}
            <TextField autoFocus margin="normal" inputRef={emailRef} type="email" id="email" label="Email" sx={textFieldStyle} />
            <TextField margin="normal" inputRef={passwordRef} type="password" id="password" label="Password" sx={textFieldStyle} />
            <LoadingButton
              sx={{ mt: '16px', mb: '4px', width: '150px' }}
              loading={loading}
              variant="contained"
              type="submit"
            >
              Sign In
            </LoadingButton>
          </Box>
        </form>
        <Typography variant="subtitle1" align="center" sx={{ mt: '10px' }}>
          <Link to="/forgot-password">Forgot Password?</Link>
        </Typography>
      </Card>
      <Box>
        <Typography variant="subtitle1" align="center" sx={{ mt: '10px' }}>
          Need an account?
          {' '}
          <Link to="/SignUp">Sign Up</Link>
        </Typography>
      </Box>
    </Box>
  );
}

根據文檔,您必須將disabled屬性傳遞給LoadingButton組件。 將其設置為與您的loading狀態相同。

<LoadingButton 
  sx={{ mt: '16px', mb: '4px', width: '150px' }} 
  loading={loading} 
  disabled={loading}
  variant="contained" 
  type="submit"
>
  Sign In
</LoadingButton>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM