_Note _-> Arrow function inside a class and function takes it's scope but the same arrow function inside an object will not take it's scope but the outermost function scope or the global scope(in case of global scope)
Class Component
Constructor Binding ->
import React from "react";
class BindHandler extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
this.decrementCount = this.decrementCount.bind(this);
}
decrementCount() {
this.setState({ count: this.state.count - 1 });
}
render() {
return (
<>
<h1>{this.state.count}</h1>
<button onClick={this.decrementCount}>Decrement</button>
</>
);
}
}
export default BindHandler;
Arrow Function Binding where the function itself is Arrow function ->
Note that we don't need any constructor binding here as arrow function always takes the scope of the outer function.
import React from "react";
class BindHandler extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<>
<h1>{this.state.count}</h1>
<button onClick={this.incrementCount}>Increment</button>
</>
);
}
}
export default BindHandler;
Normal Function -> converted to arrow function ->
import React from "react";
class BindHandler extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
decrementCount() {
this.setState({ count: this.state.count - 1 });
}
render() {
return (
<>
<h1>{this.state.count}</h1>
<button onClick={() => this.decrementCount()}>Decrement</button>
</>
);
}
}
export default BindHandler;
Top comments (0)