1
class CheckBox extends React.Component{
  constructor(checked){
    super(checked);
    this.state={checked:false}
  }
  handleChange(event){
    this.setState({checked:!this.state.checked});
  }
  render(){
    var msg;
    if(this.state.checked){
      msg= "checked"
    }else{
      msg="unchecked"
    }
    return(
      <div>
        <input type="checkbox" onChange={this.handleChange} />
        <h3>Checkbox is {msg}</h3>
      </div>
    );
  }
}

it said

TypeError: Cannot read property 'setState' of undefined

i don't know the reason

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
F111
  • 11
  • 1
  • You have to bind your `handleChange()` function. You can do it in the constructor: `this.handleChange = this.handleChange.bind(this);` – Jayce444 Apr 26 '18 at 09:03

1 Answers1

3

Either bind this to your function in the constructor

constructor(checked){
    super(checked);
    this.state={checked:false}

    this.handleChange = this.handleChange.bind(this);

}

See https://jsfiddle.net/gaby/chazb1ju/


Or pass an arrow function when binding the handler to the event

<input type="checkbox" onChange={(e)=>this.handleChange(e)} />

See https://jsfiddle.net/gaby/sjjrrtsu/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317