samedi 3 octobre 2015

React checkbox doesn't toggle

When I click the checkbox, the check mark doesn't disappear although the console.log in the onChange handler indicates the state changed to false. On the other hand, when the state is changed by a separate button, the check mark properly toggles on and off.

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();
    console.log(event.target.checked);  // This logs 'false' meaning click did change the state
    this.setState({is_checked: !this.state.is_checked});
}
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>
    );
}
}




Aucun commentaire:

Enregistrer un commentaire