gpt4 book ai didi

javascript - React - 复选框输入未正确更新(由于浅合并)

转载 作者:行者123 更新时间:2023-11-30 14:14:22 25 4
gpt4 key购买 nike

我认为由于浅合并,我的代码中存在一些错误,尤其是我的复选框,因为它的行为很奇怪。有人可以就如何修复它提出一些建议吗?

这就是我设置状态和处理输入变化的方式:

state = {
form: {
firstName: "",
lastName: "",
email: "",
password: "",
rememberMe: false
}
};

handleChange = e => {
const { name, value, checked } = e.target;
const isCheckbox = checked === "checkbox";
this.setState(prevState => ({
form: {
// all other key value pairs of form object
...prevState.form,

// update this one specifically
[name]: isCheckbox ? checked : value
}
}));
};

提交和验证

  validateForm = () => {
const formInputs = ["firstName", "lastName", "email", "password", "rememberMe"];

for (let i = 0; i < formInputs.length; i++) {
const inputName = formInputs[i];

if (!this.state.form[inputName].length) {
return false;
}
}

return true;
};

handleSubmit = () => {
if (this.validateForm()) {
console.log("Success!");
console.log(this.state);
} else {
console.log("Failure!");
}
};

这是我的表单的片段:

   <form
className="Form"
onSubmit={e => {
e.preventDefault();
this.handleSubmit();
}}
>
<input name="firstName" onChange={this.handleChange} />
<input name="lastName" onChange={this.handleChange} />
<input name="email" onChange={this.handleChange} />
<input name="password" onChange={this.handleChange} />
<input
name="rememberMe"
type="checkbox"
checked={this.state.form.rememberMe}
onChange={this.handleChange}
/>
<button className="no-padding">Submit</button>
</form>

提交后设法获得“成功”,但我的复选框表现异常并保持选中状态。

最佳答案

我觉得应该是

 const { name, value, checked, type } = e.target;
const isCheckbox = type === "checkbox";

或者

 const { name, value, checked } = e.target;
const isCheckbox = name === "rememberMe";

关于javascript - React - 复选框输入未正确更新(由于浅合并),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53841797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com