英文:
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实体(如"
和<
)替换为普通的双引号和尖括号,以便于理解和运行。
英文:
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 "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>
First Name:
<input
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>{" "}
<br />
Last Name:{" "}
<input
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>{" "}
<br />
{fullName}
<br />
<button value={resetName}>Reset!</button>
</div>
);
}
答案1
得分: 3
调用 setFirstName
和 setLastName
来重置输入值。
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
function resetName() {
setFirstName("");
setLastName("");
}
并设置 <button>
的 onClick
属性:
<button onClick={resetName}>重置!</button>
英文:
Call setFirstName
and setLastName
to reset the input values.
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
function resetName() {
setFirstName("");
setLastName("");
}
And set the onClick
attribute of the <button>
:
<button onClick={resetName}>Reset!</button>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论