简体   繁体   中英

Changing the state of a checkbox with setState

I have a component and i am able to change the state of checkbox item when i click on a button. I also want to be able to change the state in another button-click, which has lot more logic in it. The issue i am having in that when the code goes into the condition it does not set the state back to false.

I tried changing the state again using setstate but it does not change the state of the enabledCheckBox.

this.setState({
  enabledCheckBox: !this.state.enabledCheckBox,
})

Can anyone tell me what the issue is? Thanks

class Customer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      ...props,
      enabledCheckBox: false
    };
  }

  //this works    
  onChangeCheckBox=()=>{
    this.setState({
      enabledCheckBox: !this.state.enabledCheckBox,
    })
  }

  //cant get this to work
  handleCustomerClick = (event) => {

    if (this.state.enabledCheckBox) {      
      this.setState({
        enabledCheckBox: !this.state.enabledCheckBox,
      })
    }

your this is being bound incorrectly try this;

handleCustomerClick = (event) => {
  let {enabledCheckBox} = this.state;

  this.setState({
    enabledCheckBox: !enabledCheckBox,
  });
}

If you really need the if statement you could do the following;

handleCustomerClick = (event) => {
  let {enabledCheckBox} = this.state;
  let data;

  if (enabledCheckBox) {
    data = {
      enabledCheckBox: !enabledCheckBox
    }
  }

  this.setState(data);
}

https://codesandbox.io/s/1y0zywy727

I included a working example. It does similar things as how you described.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      enabledCheckBox: false
    };
  }

  onClick = () => {
    this.setState({ enabledCheckBox: !this.state.enabledCheckBox });
  };

  render() {
    return (
      <div>
        <input
          type="checkbox"
          value={"some checked box"}
          checked={this.state.enabledCheckBox}
          onChange={this.onClick}
        />
        {this.state.enabledCheckBox ? <div>Blue</div> : <div>Red</div>}
        <button onClick={this.onClick}>Click to Change Color</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Both input and div are using this.state.enabledcheckbox . So if you check the box, not only the box will be checked but also the div 's "color" would change with it. Same thing as clicking the button

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM