提交表单时弹出提醒

问题描述 投票:0回答:1

我想在提交表单时显示弹出警报,但它没有按预期工作。当我刷新页面时,警报弹出窗口不会自行隐藏;相反,即使页面重新加载后它也会继续显示。我希望仅当表单提交成功且没有任何错误时才出现弹出窗口。下面是我的代码:

首先,我将 isModalOpen 设置为 false

const [isModalOpen, setIsModalOpen] = useState(false)

在handleSubmit函数中,这是我的代码

function handleSubmit(e){
    e.preventDefault();
    let hasError = false;

    // if there is no error, the form will be submitted
    if(!hasError){
      setIsModalOpen(true)

    if(firstName.trim() === ''){
      setFirstNameError('This field is required')
      hasError = true;
    }
    if(emailAddress.trim() === ''){
      setEmailError('Please enter a valid email address')
      hasError = true;
    }
    if(message.trim() === ''){
      setMessageError('This field is required')
      hasError = true;
    }
    }

}

最后这是我的代码,它呈现弹出消息,表单提交没有错误

{isModalOpen && (
       <div id='overlay'>
        <div className={`pop-up`}>
          <div className='flex gap-2 check'>
            <img src="./images/icon-success-check.svg" alt="" />
            <p>Message Sent!</p>
        </div>
  
        <p className='relative ml-[20px]'>Thanks for completing the form. We'll be in touch soon!</p>
        </div>
      </div>
    )}
javascript html css reactjs if-statement
1个回答
0
投票

因为

isModalOpen

块引用

页面重新加载后状态会保留,或者表单验证逻辑的结构存在问题。

const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // Reset error states
    setFirstNameError('');
    setEmailError('');
    setMessageError('');

    let hasError = false;

    if (firstName.trim() === '') {
      setFirstNameError('This field is required');
      hasError = true;
    }

    if (emailAddress.trim() === '') {
      setEmailError('Please enter a valid email address');
      hasError = true;
    }

    if (message.trim() === '') {
      setMessageError('This field is required');
      hasError = true;
    }

    if (!hasError) {
      setIsModalOpen(true);
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.