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粉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>