以下是我目前的代码,它输出了我输入的名称,但我想创建一个重置按钮,将状态清空为一个空状态
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
调用setFirstName
和setLastName
来重置输入值。
const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); function resetName() { setFirstName(""); setLastName(""); }
并设置<button>
的onClick
属性:
<button onClick={resetName}>重置!</button>