-4

Hello guys, so I found interesting task about React, and I a little bit don't understand how to solve it


Task: Why this code is not working? Solve this.

Code:

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1
    }
  }
  handler() {
    this.setState({count: this.state.count++})
  }
  render() {
    console.log('render')
    return (
      <div>
        <button onClick={this.handler}>Add 1</button>
        <p>{this.state.count}</p>
      </div>
    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById("test"));
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="test"></div>
</body>
</html>

1 Answers1

3

You sent wrong function reference. It should be like this.

<button onClick={this.handler.bind(this)}>Add 1</button>

or

<button onClick={() => this.handler()}>Add 1</button>
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
TopWebGhost
  • 335
  • 1
  • 8