Why is this in click2 undefined?

    constructor() {
        super();
        this.name = "MyComponent";

        this.handleClick2 = this.handleClick1.bind(this);
    }

    handleClick1() {
        console.log(this)
        alert(this.name);
    }

    handleClick3 = () => alert(this.name);
    render() {
        return (
            <div>
                <button onClick={this.handleClick1()}>click 1</button>
                <button onClick={this.handleClick1}>click 2</button>
                <button onClick={this.handleClick2}>click 3</button>
                <button onClick={this.handleClick3}>click 4</button>
            </div>
        );
    }
}
Dec.15,2021

first of all, there is something wrong with your description. The this of your click1 is undefined, not click2.

you can change your code like this.

  

first of all, you need to know the meaning of this definition method: the definition of
handleClick1 is defined on prototype, and you give it to a button directly. When it executes, you don't know which instance is calling it, so it is undefined.
you can use this. HandleClick1.bind (this) is one way to pass this in.
in addition, there are two other ways of writing you above, one is the arrow function, and the other is to define the function on this.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ead5d1-47f14.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ead5d1-47f14.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?