Wednesday, January 1, 2020

[ReactJs][Resolved] Uncaught TypeError: Cannot read property 'state' of undefined


Error message:
Uncaught TypeError: Cannot read property 'state' of undefined
Source code:
<div id="root"></div>
<script type="text/babel">
class Button extends React.Component{
  constructor(props){
    super(props);
    this.state = {isToggleOn:true}
  }
  handleClick() {
    console.log(this.state.isToggleOn);
  }
  render(){
    return <button onClick={this.handleClick}>Click</button>
  }
}
ReactDOM.render(
  <Button />,
  document.getElementById('root')
);
</script>
Use binding to make `this` work in handleClick callback.
<div id="root"></div>
<script type="text/babel">
class Button extends React.Component{
  constructor(props){
    super(props);
    this.state = {isToggleOn:true}
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log(this.state.isToggleOn);
  }
  render(){
    return <button onClick={this.handleClick}>Click</button>
  }
}
ReactDOM.render(
  <Button />,
  document.getElementById('root')
);
</script>

No comments :

Post a Comment