当我单击复选框时,虽然onChange处理程序中的console.log指示状态更改为false,但复选标记并不会消失。另一方面,当通过单独的按钮改变状态时,复选标记正确地打开和关闭。反应复选框不会切换
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>
);
}
}
我知道它已经有一段时间,但接受的答案是某种误导(虽然没有错)。此外,我认为你不应该用双向绑定来解决这个问题,就像你在自己的答案中一样。 – ftor