繁体   English   中英

如何重置reactjs中的输入字段?

[英]How to reset input field in reactjs?

当用户提交三个项目时,我尝试重置输入字段。 但我不明白。 这是我的代码。

 const onSubmit = (myData) => { const url = "https://automobilereact.herokuapp.com/product"; const newData = { ...myData, sold: 0 }; fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newData), }) .then((res) => res.json()) .then((result) => console.log(result)); const { data } = axios.post("https://automobilereact.herokuapp.com/add-item", { ...myData, email: user.email, sold: 0, }); };

有多种解决方案,但这是最好的方法

将输入绑定到一个状态:

const [inputContent, setInputContent] = useState("Default value")

输入代码:

<input onChange={(e) => setInputContent(e.target.value)} value={inputContent} />

提交时删除inputContent

const onSubmit = (myData) => {
  setInputContent("")
  // Rest of code...
  };

 const onSubmit = (myData) => { const url = "https://automobilereact.herokuapp.com/product"; const newData = { ...myData, sold: 0 }; fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newData), }) .then((res) => res.json()) .then((result) => console.log(result)); const { data } = axios.post("https://automobilereact.herokuapp.com/add-item", { ...myData, email: user.email, sold: 0, }); // Try this out.... let inputs = document.getElementById("id"); inputs.value = ""; };

对每个输入字段使用此方法。 只需将它们的值设置为空。 像这样...

let inputs = document.getElementById("id");
 inputs.value = "";
  };

记住在 post 方法的最后使用它们。 如果您在发布值之前使用它,您的数据将被发送为空。

暂无
暂无

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

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