加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

“React”复选框不会切换

发布时间:2020-12-15 20:51:24 所属栏目:百科 来源:网络整理
导读:当我单击复选框时,复选标记不会消失,尽管onChange处理程序中的console.log指示状态更改为false.另一方面,当通过单独的按钮改变状态时,复选标记正确地切换和切换. export default class TestComponent extends Component {constructor(props) { super(props);
当我单击复选框时,复选标记不会消失,尽管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>
    );
}
}
我想我看到发生了什么.

您单击按钮,它将切换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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读