I am a React newbie, and am working on examples from Adam Freeman's book.
I am starting with simple event handling and am unable to figure out why the regular-looking version of handleClick() below does not work. The method using the arrow notation (from the book) works as expected, but I am trying to translate it to the standard method notation, and am unable to figure out what is missing.
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 4
}
}
isEven(val) { return val % 2 === 0 ? "Even" : "Odd"; }
// the following works
//handleClick = () => this.setState({ count: this.state.count + 1 });
// this gives an error: TypeError: Cannot read property 'setState' of undefined
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render = () =>
<h4>
<button onClick={this.handleClick}>Click me!</button>
Number of items: {this.isEven(this.state.count)}
</h4>
}
What changes are needed for handleclick() to work?