当我单击复选框时,复选标记不会消失,尽管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> ); } }
我想我看到发生了什么.
原文链接:https://www.f2er.com/react/301148.html您单击按钮,它将切换is_checked,它可以选中或取消选中该框.但是最终触发一个onChange的复选框,这也可以切换状态…你实际上编码了一个无限循环.虽然,由于React批次/ debounces setState操作,您的代码不会锁定您的页面.
尝试这个:
var React = require("react"); var Component = React.createClass({ getInitialState: function() { return { isChecked: true }; },handleCheckBoxChange: function(event) { console.log("checkBox changed!",event); this.setState({isChecked: event.target.checked}); },toggleIsChecked: function() { console.log("toggling isChecked value!"); this.setState({isChecked: !this.state.isChecked}); },handleButtonClick: function(event) { console.log("button was pressed!",event); this.toggleIsChecked(); },render: function() { return ( <div> <input type="checkBox" onChange={this.handleCheckBoxChange} checked={this.state.isChecked} /> <button onClick={this.handleButtonClick}>change checkBox state using this button</button> </div> ); } }); module.exports = Component;
请注意,您可以使用React的valueLink使此代码更干净(请阅读更多:https://facebook.github.io/react/docs/two-way-binding-helpers.html)