两个输入字段中的一个只接受一个字母,并自动提交表单。为什么?

huangapple go评论86阅读模式
英文:

Among two input fields one is taking just one letter and submit the form automatically. Why?

问题

我正在进行一个MERN博客网站项目的工作。在“写博文”部分有两个输入字段。一个是标题,另一个是描述。

当我尝试写博文时,标题可以完整地输入,但是当我尝试写描述时,只输入一个字母后,表单会自动提交。

如果我先尝试写描述,它也会接受几个单词,但是这次标题只接受一个字母,并在我尝试输入第二个字母时自动提交表单。

我在这里附上了我的代码!
你能帮我解决这个问题吗?

import { useContext, useState } from "react";
import "./write.css";
import { Context } from "../../context/Context";
import axios from "axios";

export default function Write() {
    const [title, setTitle] = useState("");
    const [desc, setDesc] = useState("");
    const [file, setFile] = useState(null);
    const { user } = useContext(Context);

    const handleSubmit = async (e) => {
        e.preventDefault();
        const newPost = {
            username: user.username,
            title,
            desc,
        };
        if (file) {
            const data = new FormData();
            const filename = Date.now() + file.name;
            data.append("name", filename);
            data.append("file", file);
            newPost.photo = filename;
            try {
                await axios.post("/upload", data);
            } catch (err) {}
        }
        try {
            const res = await axios.post("/posts", newPost);
            window.location.replace("/post/" + res.data._id);
        } catch (err) {
            
        }
    };
  return (
      <div className="write">
          {file && 
          <img src={URL.createObjectURL(file)} alt="" className="writeImg" />
          }
          <form className="writeForm" onChange={handleSubmit}>
              <div className="writeFormGroup">
                  <label htmlFor="fileInput">
                     <i class="writeIcon fa-solid fa-plus"></i>
                  </label>
                  <input type="file" id="fileInput" style={{display:"none"}} onChange={(e)=> setFile(e.target.files[0])} />
                  <input type="text" placeholder="Title" className="writeInput" autoFocus={true} onChange={e=> setTitle(e.target.value)} />
              </div>
              <div className="writeFormGroup">
                  <textarea placeholder="Tell your story..." type="text" className="writeInput writeText" onChange={e=> setDesc(e.target.value)}></textarea>
              </div>
              <button className="writeSubmit" type="submit">Publish</button>
          </form>
      </div>
  )
}
英文:

I was working on a MERN blog website project. In the Write post section there are two input fields. One is for Title & another is for description.
When I try to write a post the title can be written fully but when I try to write the description the form getting submitted automatically after typing just one letter.

If I try to write the description first it also taking several word but this time the title is taking one letter and submitting the form automatically as sson as I try to type the second letter.

I'm attaching my code here!
Can you please help me to solve this issue?

import { useContext, useState } from &quot;react&quot;
import &quot;./write.css&quot;;
import {Context} from &quot;../../context/Context&quot;;
import axios from &quot;axios&quot;;
export default function Write() {
const [title, setTitle] = useState(&quot;&quot;);
const [desc, setDesc] = useState(&quot;&quot;);
const [file, setFile] = useState(null);
const { user } = useContext(Context);
const handleSubmit = async (e) =&gt; {
e.preventDefault();
const newPost = {
username: user.username,
title,
desc,
};
if (file) {
const data = new FormData();
const filename = Date.now() + file.name;
data.append(&quot;name&quot;, filename);
data.append(&quot;file&quot;, file);
newPost.photo = filename;
try {
await axios.post(&quot;/upload&quot;, data);
} catch (err) {}
}
try {
const res = await axios.post(&quot;/posts&quot;, newPost);
window.location.replace(&quot;/post/&quot; + res.data._id);
} catch (err) {
}
};
return (
&lt;div className=&quot;write&quot;&gt;
{file &amp;&amp; 
&lt;img src={URL.createObjectURL(file)} alt=&quot;&quot; className=&quot;writeImg&quot; /&gt;
}
&lt;form className=&quot;writeForm&quot; onChange={handleSubmit}&gt;
&lt;div className=&quot;writeFormGroup&quot;&gt;
&lt;label htmlFor=&quot;fileInput&quot;&gt;
&lt;i class=&quot;writeIcon fa-solid fa-plus&quot;&gt;&lt;/i&gt;
&lt;/label&gt;
&lt;input type=&quot;file&quot; id=&quot;fileInput&quot; style={{display:&quot;none&quot;}} onChange={(e)=&gt; setFile(e.target.files[0])} /&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;Title&quot; className=&quot;writeInput&quot; autoFocus={true} onChange={e=&gt; setTitle(e.target.value)} /&gt;
&lt;/div&gt;
&lt;div className=&quot;writeFormGroup&quot;&gt;
&lt;textarea placeholder=&quot;Tell your story...&quot; type=&quot;text&quot; className=&quot;writeInput writeText&quot; onChange={e=&gt; setDesc(e.target.value)}&gt;&lt;/textarea&gt;
&lt;/div&gt;
&lt;button className=&quot;writeSubmit&quot; type=&quot;submit&quot;&gt;Publish&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
)
}

答案1

得分: 1

在你的表单中,你应该将这个代码改成:<form className="writeForm" onSubmit={handleSubmit}>,而不是<form className="writeForm" onChange={handleSubmit}>
onChange改为onSubmit应该可以解决这个问题。

英文:

In your form, you should change this: &lt;form className=&quot;writeForm&quot; onChange={handleSubmit}&gt; to this: &lt;form className=&quot;writeForm&quot; onSubmit={handleSubmit}&gt;.
Changing onChange to onSubmit should solve the issue

huangapple
  • 本文由 发表于 2023年8月9日 01:49:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定