click2 中的this 为什么是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>
        );
    }
}
阅读 3.8k
6 个回答

首先你的描述有问题,是你的click1的this为undefined 不是click2。

你可以将你的代码改成这样就好了。

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

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

是因为上下文丢了

react的事件默认是没有绑定上下文的,this默认为undefined,需要手动给事件绑定this

因为你的click1没有绑定到 this,所以click2也没有。

建议使用箭头函数=> , 可以解决问题。

首先需要知道这种定义方法的含义:
handleClick1的这种定义是定义在prototype上的,你直接把它给一个按钮,它执行的时候,是不知道哪个实例在调用它,所以是undefined。
可以通过this. handleClick1.bind(this)的方式把this传递进去,这是一种方式。
另外就是你上面的其他两种写法,一个是箭头函数,一个是在this上定义函数。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题