问题描述
这肯定是一个关于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>
解决方法
您正在混淆名称。 在初始状态下,您将:
const [newUser,setNewUser] = useState({
userName: "",email: "",password: "",error: null,});
但是在更改值时,您将值设置为userName
,userEmail
和userPassword
。如下面的JSX中所述,您添加了每个字段的name
属性。
同步名称,您就可以开始了!