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

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

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

问题

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

import { useState } from "react";

function resetName() {
  this.firstName.value = "";
  this.lastName.value = "";
}
export default function Test() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");

  const fullName = `${firstName} ${lastName}`;

  return (
    <div>
      名字
      <input
        value={firstName}
        onChange={(e) => setFirstName(e.target.value)}
      />{" "}
      <br />
      姓氏{" "}
      <input
        value={lastName}
        onChange={(e) => setLastName(e.target.value)}
      />{" "}
      <br />
      {fullName}
      <br />
      <button onClick={resetName}>重置</button>
    </div>
  );
}

注意:我已经将代码中的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

import { useState } from &quot;react&quot;;

function resetName() {
  this.firstName.value = &quot;&quot;;
  this.lastName.value = &quot;&quot;;
}
export default function Test() {
  const [firstName, setFirstName] = useState(&quot;&quot;);
  const [lastName, setLastName] = useState(&quot;&quot;);

  const fullName = `${firstName} ${lastName}`;

  return (
    &lt;div&gt;
      First Name:
      &lt;input
        value={firstName}
        onChange={(e) =&gt; setFirstName(e.target.value)}
      /&gt;{&quot; &quot;}
      &lt;br /&gt;
      Last Name:{&quot; &quot;}
      &lt;input
        value={lastName}
        onChange={(e) =&gt; setLastName(e.target.value)}
      /&gt;{&quot; &quot;}
      &lt;br /&gt;
      {fullName}
      &lt;br /&gt;
      &lt;button value={resetName}&gt;Reset!&lt;/button&gt;
    &lt;/div&gt;
  );
}



答案1

得分: 3

调用 setFirstNamesetLastName 来重置输入值。

const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
function resetName() {
    setFirstName("");
    setLastName("");
}

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

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

Call setFirstName and setLastName to reset the input values.

const [firstName, setFirstName] = useState(&quot;&quot;);
const [lastName, setLastName] = useState(&quot;&quot;);
function resetName() {
	setFirstName(&quot;&quot;);
	setLastName(&quot;&quot;);
}

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

&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:

确定