Constructor
The constructor
method is a special method that is automatically called when a component is being created.
It is used to initialize the component's state and bind event handlers.
In the example below, the constructor
method is used to initialize the count
state to 0 and bind the handleIncrement
event handler:
JAVASCRIPT
1// The constructor method is used to initialize state and bind event handlers
2
3class MyComponent extends React.Component {
4 constructor() {
5 // Call the super method to invoke the parent constructor
6 super();
7
8 // Initialize the component's state
9 this.state = {
10 count: 0
11 };
12
13 // Bind event handlers
14 this.handleIncrement = this.handleIncrement.bind(this);
15 }
16
17 handleIncrement() {
18 // Update the state by incrementing the count
19 this.setState(prevState => ({
20 count: prevState.count + 1
21 }));
22 }
23
24 render() {
25 return (
26 <div>
27 <h1>Counter: {this.state.count}</h1>
28 <button onClick={this.handleIncrement}>Increment</button>
29 </div>
30 );
31 }
32}
xxxxxxxxxx
32
}
// The constructor method is used to initialize state and bind event handlers
class MyComponent extends React.Component {
constructor() {
// Call the super method to invoke the parent constructor
super();
// Initialize the component's state
this.state = {
count: 0
};
// Bind event handlers
this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {
// Update the state by incrementing the count
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.handleIncrement}>Increment</button>
</div>
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment