简体   繁体   English

当 onBlur 事件上的按钮消失时,如何使表单提交工作? 反应,下一个js

[英]How do I make a form submit work when button disappears on onBlur event? React, next js

I have a form which performs an event on submit.我有一个在提交时执行事件的表单。

The form contains a textarea, that when you click on it, the submit button appears, and when you click out it disappears (using onFocus and onBlur for this to flag variable 'showSubmit'):该表单包含一个文本区域,当您单击它时,会出现提交按钮,当您单击它时它会消失(使用onFocusonBlur来标记变量“showSubmit”):

 <form id="commentsForm" onSubmit={handleSubmitForm}>... <textarea onFocus={onFocusShowSubmit} onBlur={onBlurHideSubmit} id="comment" name="comment" type="text" required></textarea> {showSubmit? <button type="submit">Post Comment</button>: null} </form>

The onBlur event is blocking the button to be clicked and therefore to submit the form. onBlur 事件阻止单击按钮并因此提交表单。

I read about using onMouseDown event in the button, and it does work, but it does not capture the form event.我阅读了有关在按钮中使用onMouseDown事件的信息,它确实有效,但它没有捕获表单事件。 And I really need to pass the form event to the "handleSubmitForm" to be able to retrieve the form data..我真的需要将表单事件传递给“handleSubmitForm”才能检索表单数据..

Does anybody know how I could work this out?有人知道我怎么能解决这个问题吗? Thanks!谢谢!

I reproduced this and solved it this way:我复制了这个并以这种方式解决了它:

import React, { useState } from "react";

function Q1() {
  const [showSubmit, setShowSubmit] = useState(false);
  const [text, setText] = useState();

  const onFocusShowSubmit = () => {
    setShowSubmit(true);
  };

  const handleSubmitForm = (e) => {
    alert("Form Sent");
  };
  return (
    <div>
      <form id="commentsForm" onSubmit={handleSubmitForm}>
        ...
        <textarea
          onFocus={onFocusShowSubmit}
          onBlur={
            text && text.length >= 1
              ? () => setShowSubmit(true)
              : () => setShowSubmit(false)
          }
          id="comment"
          name="comment"
          type="text"
          required
          onChange={(e) => setText(e.target.value)}
        >
          {text}
        </textarea>
        {showSubmit ? <button type="submit">Post Comment</button> : null}
      </form>
    </div>
  );
}

export default Q1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM