简体   繁体   中英

ReactJS: State is not changing

class Checkbox extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      checked: true
    }
  }
  changeClick()  {
    this.setState({checked: !this.state.checked})
  }
  render() {
    var chk;
    if(this.state.checked){
      chk='Checked';
    }else{
      chk='Unchecked'
    }
    return (
       <div>
         <h2>Checkbox is {chk}</h2>
         <input type='checkbox' onChange={this.changeClick} defaultChecked=
         {this.state.checked}/>
      </div>
  )
  }
}
ReactDOM.render(
  <Checkbox />,
  document.getElementById("root")
);

I'm new to React and trying to learn ES2015 too, can somebody help me with this, why State is not changing in this snippet.

Any help would be appreciated thank you :)

You can use an anonymous function to bind this

  changeClick = () =>  {
    this.setState((prevState)=>{return {checked:!prevState.checked}})
  }

Also, check the console in the browser to see errors. Then you can search for answers to the error, this is a very common one.

Edit: updated based on comment

The issue is due to unavailability of this inside changeClick() . this is undefined inside the function. to avoid this you can bind this method inside the constructor

this.changeClick = this.changeClick.bind(this);

or

Use es6 arrow functions

changeClick = () =>  {
    this.setState({checked: !this.state.checked})
  }

see the fiddle given below https://jsfiddle.net/yxzyp7yq/?utm_source=website&utm_medium=embed&utm_campaign=yxzyp7yq

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