【发布时间】:2020-05-12 11:57:12
【问题描述】:
我开始使用 Hooks,并且我有一个带有多个输入的 useState 对象。我想了解的是如何在提交表单后清除输入值。
在 sumbit 函数 I setInput({ Input1: "", Input2: "" }); 上,这实际上会清除对象值,但不会清除输入值。
另外,不知道为什么console.log(input); 会出现多次。
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [input, setInput] = useState({ Input1: "", Input2: "" });
const [button, setButton] = useState("Button");
console.log(input);
const _handleChange = e => {
setInput({ ...input, [e.target.name]: e.target.value });
};
function _handleSubmit(e) {
e.preventDefault();
setInput({ Input1: "", Input2: "" });
setButton("Submitted");
setTimeout(() => setButton("Button"), 1000);
console.log("Submitted");
}
return (
<form onSubmit={_handleSubmit}>
<input
type={"text"}
placeholder={"Input1"}
name={"Input1"}
onChange={_handleChange}
/>
<input
type={"text"}
placeholder={"Input2"}
name={"Input2"}
onChange={_handleChange}
/>
<button text="Save" type="submit">
{button}
</button>
</form>
);
}
【问题讨论】:
标签: reactjs react-hooks