我开始玩Hooks,我有一个带有多个输入的useState对象。我想了解的是如何在提交表单后清除输入值。
在sumbit函数中,我 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>
);
}
目前,你的 input
是 旁门左道它不知道状态 input.Input1
办理 _handleChange
.
尝试添加一个 value
的道具。
<input value={input.Input1} onChange={_handleChange} />
此外,该日志两次出现在 _handleSubmit
因为你改变了两次状态。
setInput({ Input1: '', Input2: '' });
setButton('Submitted');
timeout
变化后的状态 1000ms
- 导致一次渲染和第二次记录。setTimeout(() => setButton('Button'), 1000);