React之this绑定

一、首先看一下没有绑定this的情况

class App extends React.Component{
constructor(props){
super(props)
console.log('构造函数内部',this)
this.state = {
dateId: new Date().toLocaleTimeString()
}
}

handleClick(){
console.log('函数内部',this)
}

render() {
return (
<div>
<a href="" onClick={this.handleClick()}>hello,word!</a>
<p>{this.state.dateId}</p>
</div>
);
}
}

此时,打印出的this均指向组件App,并且handleClick函数是在原型链__proto__上的,即handleClick时原型方法

当点击事件,将函数作为值来传入的时候,点击之后,“函数内部”的this返回undefined

    render() {
        return (
            <div>
                <a href="" onClick={this.handleClick}>hello,word!</a>
                <p>{this.state.dateId}</p>
            </div>
        );
    }

究其原因,根据属性的查找机制,沿原型链由近及远查找,

  1、

猜你喜欢

转载自www.cnblogs.com/yuam/p/10903319.html