如何在React.js中使用useState重置我的输入标签

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

How to Reset my input tags in react.js using useState

问题

以下是我到目前为止的代码,它会输出,但我输入了名字,但我想创建一个重置按钮,将状态清除为一个空状态。

  1. import { useState } from "react";
  2. function resetName() {
  3. this.firstName.value = "";
  4. this.lastName.value = "";
  5. }
  6. export default function Test() {
  7. const [firstName, setFirstName] = useState("");
  8. const [lastName, setLastName] = useState("");
  9. const fullName = `${firstName} ${lastName}`;
  10. return (
  11. <div>
  12. 名字
  13. <input
  14. value={firstName}
  15. onChange={(e) => setFirstName(e.target.value)}
  16. />{" "}
  17. <br />
  18. 姓氏{" "}
  19. <input
  20. value={lastName}
  21. onChange={(e) => setLastName(e.target.value)}
  22. />{" "}
  23. <br />
  24. {fullName}
  25. <br />
  26. <button onClick={resetName}>重置</button>
  27. </div>
  28. );
  29. }

注意:我已经将代码中的HTML实体(如&quot;&lt;)替换为普通的双引号和尖括号,以便于理解和运行。

英文:

Below is the code I have so far it outputs but I put in the names however I want to create a reset buttons that clears the state back to a empty state

  1. import { useState } from &quot;react&quot;;
  2. function resetName() {
  3. this.firstName.value = &quot;&quot;;
  4. this.lastName.value = &quot;&quot;;
  5. }
  6. export default function Test() {
  7. const [firstName, setFirstName] = useState(&quot;&quot;);
  8. const [lastName, setLastName] = useState(&quot;&quot;);
  9. const fullName = `${firstName} ${lastName}`;
  10. return (
  11. &lt;div&gt;
  12. First Name:
  13. &lt;input
  14. value={firstName}
  15. onChange={(e) =&gt; setFirstName(e.target.value)}
  16. /&gt;{&quot; &quot;}
  17. &lt;br /&gt;
  18. Last Name:{&quot; &quot;}
  19. &lt;input
  20. value={lastName}
  21. onChange={(e) =&gt; setLastName(e.target.value)}
  22. /&gt;{&quot; &quot;}
  23. &lt;br /&gt;
  24. {fullName}
  25. &lt;br /&gt;
  26. &lt;button value={resetName}&gt;Reset!&lt;/button&gt;
  27. &lt;/div&gt;
  28. );
  29. }

答案1

得分: 3

调用 setFirstNamesetLastName 来重置输入值。

  1. const [firstName, setFirstName] = useState("");
  2. const [lastName, setLastName] = useState("");
  3. function resetName() {
  4. setFirstName("");
  5. setLastName("");
  6. }

并设置 &lt;button&gt;onClick 属性:

  1. &lt;button onClick={resetName}&gt;重置!&lt;/button&gt;
英文:

Call setFirstName and setLastName to reset the input values.

  1. const [firstName, setFirstName] = useState(&quot;&quot;);
  2. const [lastName, setLastName] = useState(&quot;&quot;);
  3. function resetName() {
  4. setFirstName(&quot;&quot;);
  5. setLastName(&quot;&quot;);
  6. }

And set the onClick attribute of the &lt;button&gt;:

  1. &lt;button onClick={resetName}&gt;Reset!&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年2月8日 23:57:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388430.html
匿名

发表评论

匿名网友

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

确定