2

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??

김우동
  • 21
  • 2
  • Because handleClick is a method of the class App and you need to specify this.method to access it. You could do onClick={this.handleClick} also – Nacho Zullo Oct 08 '20 at 01:22
  • It should be `
  • this.handleClick(e)}>` or `
  • `, not `
  • this.handleClick}>`. And [referring to a local `handleClick` variable instead of the `.handleClick` property](https://stackoverflow.com/q/13418669/1048572?javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) doesn't work at all.
  • – Bergi Oct 08 '20 at 01:25
  • absolutely you are right, i edit post, But my question does not be changed... – 김우동 Oct 08 '20 at 02:22