Home  >  Q&A  >  body text

Learn how to use useState to reset input tags in react.js

The following is my current code, it outputs the name I entered, but I want to create a reset button that clears the state to an empty state

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 value={resetName}>重置!</button>
    </div>
  );
}
P粉318928159P粉318928159424 days ago562

reply all(1)I'll reply

  • P粉716228245

    P粉7162282452023-09-13 20:49:21

    Call setFirstName and setLastName to reset the input value.

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

    And set the onClick attribute of <button>:

    <button onClick={resetName}>重置!</button>
    

    reply
    0
  • Cancelreply