I have a question.. please let me know..
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
}
handleClick = () => {
console.log("clicking")
};
render() {
return (
<div>
<ul>
{this.state.letters.map((letter) => (
<li onClick={() => this.handleClick()}> // when clicking li, it works.
<li onClick={() => handleClick()}> // when clicking li, it does not works why????
hello
</li>
))}
</ul>
</div>
);
}
}
export default App;
This is very simple code.
My question is why we do write like this.handleClick ??
In my thinking,
- When clicking li tag.
- this.handleClick function is in arrow function!!
- so, arrow function binds this automatically
- (in this case, this is bound to App component)
- therefore, in arrow function, just handleClick can be found, (// in my thinking)
- Because this.handleClick can be found!
- But, just writing handleClick is not worked.. ? why ?? // handleClick does not found error...
Can you explain why this happen?
Additionally..
if I changed code like <li onClick={() => console.log(this)} />
We can see this is App component. Also in App component, we can see handleClick function...
So, this is bounded to App Component, and then I think in arrow function, handleClick() function can be found. but does not find... why??