Quando faccio clic sulla casella di controllo, il segno di spunta non scompare sebbene il console.log nel gestore onChange indichi lo stato modificato in falso. D'altra parte, quando lo stato viene modificato da un pulsante separato, il segno di spunta si attiva e disattiva correttamente.La casella di controllo React non si attiva
export default class TestComponent extends Component {
constructor(props) {
super(props);
this.state = {
is_checked: true
};
this.updateCheckbox = this.updateCheckbox.bind(this);
this.pressButton = this.pressButton.bind(this);
}
updateCheckbox(event) {
event.preventDefault();
this.setState({is_checked: !this.state.is_checked});
console.log(this.state.is_checked); // This logs 'false' meaning the click did cause the state change
console.log(event.target.checked); // However, this logs 'true' because the checkmark is still there
}
pressButton(event){
event.preventDefault();
this.setState({is_checked: !this.state.is_checked});
}
render(){
return (
<input type="checkbox" onChange={this.updateCheckbox} checked={this.state.is_checked} ></input>
<button onClick={this.pressButton}>change checkbox state using button</button>
);
}
}
So che è stato un po ', ma la risposta accettata è in qualche modo fuorviante (non male però). Inoltre, penso che non dovresti risolvere questo problema con l'associazione a due vie, come hai fatto nella tua risposta. – ftor