反应复选框不会切换 [英] React checkbox doesn't toggle

查看:63
本文介绍了反应复选框不会切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击复选框时,尽管 onChange 处理程序中的 console.log 指示状态已更改为 false,但复选标记并未消失.另一方面,当通过单独的按钮更改状态时,复选标记会正确地打开和关闭.

export default class TestComponent extends Component {构造函数(道具){超级(道具);this.state = {is_checked: 真};this.updateCheckbox = this.updateCheckbox.bind(this);this.pressButton = this.pressButton.bind(this);}更新复选框(事件){event.preventDefault();this.setState({is_checked: !this.state.is_checked});控制台日志(this.state.is_checked);//这会记录 'false' 意味着点击确实导致了状态改变console.log(event.target.checked);//但是,这会记录true",因为复选标记仍然存在}按下按钮(事件){event.preventDefault();this.setState({is_checked: !this.state.is_checked});}使成为(){返回 (<input type="checkbox" onChange={this.updateCheckbox} checked={this.state.is_checked} ></input><button onClick={this.pressButton}>使用按钮更改复选框状态</button>);}}

解决方案

我想我知道发生了什么.

您单击按钮,它会切换 is_checked,选中或取消选中该框.但这最终会触发复选框的 onChange ,这也会切换状态......您实际上已经编写了一个无限循环.虽然,由于 React 批处理/去抖动 setState 操作,您的代码不会锁定您的页面.

试试这个:

2019 年钩子 API 更新:

import React, { useState } from 'react';const 组件 = () =>{const [isChecked, setIsChecked] = useState(true);返回 (<div><输入类型=复选框"onChange={(事件)=>setIsChecked(event.currentTarget.checked)}已检查={isChecked}/><button onClick={() =>setIsChecked(!isChecked)}>使用此按钮更改复选框状态

);};

原文:

var React = require("react");var Component = React.createClass({getInitialState: 函数() {返回 {isChecked: 真};},handleCheckboxChange:函数(事件){console.log("复选框已更改!", event);this.setState({isChecked: event.target.checked});},切换IsChecked:函数(){console.log("切换 isChecked 值!");this.setState({isChecked: !this.state.isChecked});},handleButtonClick:函数(事件){console.log("按钮被按下了!", event);this.toggleIsChecked();},渲染:函数(){返回 (<div><input type="checkbox" onChange={this.handleCheckboxChange} checked={this.state.isChecked}/><button onClick={this.handleButtonClick}>使用这个按钮改变复选框状态</button>

);}});module.exports = 组件;

请注意,您可以使用 React 的 valueLink 使此代码更加简洁(在此处阅读更多信息:https://facebook.github.io/react/docs/two-way-binding-helpers.html)

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();

    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>
    );
}
}

解决方案

I think I see what's happening.

You click the button, and it toggles is_checked, which either checks or unchecks the box. But that ends up triggering an onChange for the checkbox, which also toggles the state... You've actually coded an infinite loop. Although, since React batches/debounces setState operations, your code won't lock your page up.

Try this:

2019 Update for hooks API:

import React, { useState } from 'react';

const Component = () => {
  const [isChecked, setIsChecked] = useState(true);

  return (
    <div>
      <input
        type="checkbox"
        onChange={(event) => setIsChecked(event.currentTarget.checked)}
        checked={isChecked}
      />
      <button onClick={() => setIsChecked(!isChecked)}>
        change checkbox state using this button
      </button>
    </div>
  );
};

Original:

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;

Note that you can make this code even cleaner by using React's valueLink (read more here: https://facebook.github.io/react/docs/two-way-binding-helpers.html)

这篇关于反应复选框不会切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆