當我單擊複選框時,雖然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