当我选择签入复选框时,该值应插入到爱好数组中,当我取消选中该值时,应从数组中删除该值 值正在从数组中插入和删除,但我无法直观地选中和取消选中复选框。但在州,它正在工作。
const ContactForm = () => {
const [state,setContact] = useState({
userId:"",
firstName:"",
lastName:"",
jobTitleName:"",
employeeCode:"",
emailAddress:"",
phoneNumber:"",
country:"",
status:"active",
hobbies:[]
})
const onChange = (event)=>{
setContact({...state,[event.target.name]: event.target.value});
}
e.preventDefault();
}
return (
<div className="form-group mb-2">
<label className="mb-0 font-weight-bold">Hobbies</label>
<div className="form-check">
<input type="checkbox" value="Basketball" onChange={(e)=>{
if(e.target.checked)
{
state.hobbies.push(e.target.value)
console.log(state.hobbies)
}else {
var index = state.hobbies.indexOf(e.target.value);
if (index > -1) {
state.hobbies.splice(index, 1);
console.log(state.hobbies)
}
}
}
}
/>
<label className="form-check-label">
Basketball
</label>
</div>
<div className="form-check">
<input type="checkbox" value="Vollyball" onChange={(e)=>{
if(e.target.checked)
{
state.hobbies.push(e.target.value)
console.log(state.hobbies)
}else {
var index = state.hobbies.indexOf(e.target.value);
if (index > -1) {
state.hobbies.splice(index, 1);
console.log(state.hobbies)
}
}
}
}
/>
<label className="form-check-label">
Vollyball
</label>
</div>
</div>
)
对于您的参考示例应用程序
如何使用多个复选框和添加多个值。
const checkboxes = [
'Cricket', 'Footbal', 'Tennis'
];
class App extends Component {
state = {
checkedItems: new Map(),
}
handleChange=(e)=> {
const item = e.target.name;
const isChecked = e.target.checked;
this.setState(prevState => ({ checkedItems: prevState.checkedItems.set(item, isChecked) }));
}
render() {
console.log(this.state.checkedItems)
return (
<>
{
checkboxes.map(item => (
<label key={item}>
{item}
<input type="checkbox"
checked={this.state.checkedItems.get(item)}
onChange={this.handleChange}
name={item}/>
</label>
))
}
</>
);
}
}
你正在变异状态。您的更新状态值即使用状态的方法setContact
。
请在此处找到工作代码:https://codesandbox.io/s/great-diffie-giqgr
当您在没有 useState 方法或 setState 的情况下改变状态或更改状态值时,即使您的状态值已更改,它也不会重新呈现组件。你onChange
应该是这样的。
if (e.target.checked) {
const newState = {
...state,
hobbies: [...state.hobbies, e.target.value]
};
setContact(newState);
console.log("** checked", newState);
// state.hobbies.push(e.target.value);
// console.log(state.hobbies);
} else {
const newState = {
...state,
hobbies: state.hobbies.filter(prev => prev !== e.target.value)
};
console.log("** unchecked", newState);
setContact(newState);
}