问题
I'm stuck in a sutiation where I need to disable the check boxs except the one which is checked.
The checkbox is dynamically created with the help of API and key will be passed to each checkbox. Is there a way to achieve above requirement.
Thanks
{this.state.imageinfo.map((image, key) => {
return(
<div key={key}>
<input type="checkbox"
onClick={(e)=> this.setCoverImage(e,key)}>Cover Image
<div className="delete-image" onClick={() => this.removeImage(key)}>
×
</div>
</div>
);
})
}
回答1:
You could have that checkbox change a boolean saved in state and have the disabled attribute of all the others equal to that sate object.
回答2:
use radio instead of checkbox
checkboxes behaviour is multiple selection, while radio isnt
if you want to use checkboxes:
setCoverImage(e, key) {
...
this.setState({active: key})
}
render() {
...
<input type="checkbox"
onClick={(e)=> this.setCoverImage(e,key)} checked={this.state.active === key}>
回答3:
You are required to set a checked keyword which is boolean in an array which is set in your state. When ever function is called then it will set checked keyword in only that element of Array where the key is provided. Rest of The checked keyword in Arrays will be deleted.and then you will set the Updated Array in your State. Like this.
setCoverImage=(key)=>{
const ItemKeyTobeChecked=key;
const imageinfoArray=this.state.imageinfo;
for(var i=0;i<imageinfoArray.length;i++){
if(key===i){
imageinforArray[key].checked=true;
}
else{
if(imageinforArray[i].checked){
delete imageinforArray[i].checked
}
}
}
this.setState({
imageinfo:imageinfoArray
})
}
来源:https://stackoverflow.com/questions/52853167/if-check-box-checked-disable-other-if-unchecked-enable-all-in-react