这一定是一个关于 React 钩子的老问题,但我就是不明白为什么,我用只有基本知识的钩子来改变我的代码。下面的示例格式是带有条件语句的单独状态值,适用于我的输入表单,但是:
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [userName, setUserName] = useState("");
const [error, setError] = useState(null);
const onChangeHandler = event => {
const { name, value } = event.currentTarget;
if (name === "userEmail") {setEmail(value)}
else if (name === "userPassword") {setPassword(value)}
else if (name === "userName") {setUserName(value)}
};
当我尝试像下面的示例那样将其置于单一状态时,它不起作用并直接转到错误消息:
const [newUser, setNewUser] = useState({
userName: "",
email: "",
password: "",
error: null,
});
const { userName, email, password, error } = newUser
const onChangeHandler = event => {
const { name, value } = event.currentTarget;
setNewUser({...newUser, [name]: value})
};
使用输入字段,它适用于单独的状态值,但不适用于多状态值,并且字段不可点击:
<Form.Group>
<Form.Control
size="lg"
type="text"
placeholder="Username"
name="userName"
value={userName}
onChange={event => onChangeHandler(event)}
required
/>
</Form.Group>
<Form.Group>
<Form.Control
size="lg"
type="email"
name="userEmail"
placeholder="E-mail"
value={email}
onChange={event => onChangeHandler(event)}
required
/>
</Form.Group>
<Form.Group>
<Form.Control
type={"password"}
placeholder="Password"
name="userPassword"
value={password}
onChange={event => onChangeHandler(event)}
required
/>
</Form.Group>