「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。
先上代码:
在react类组件中,事件回调上绑定一个普通函数,触发事件,普通函数上打印的this结果是undefined;
class App extends React.Component {
clickhandle(){
console.log(this)
}
render() {
return (<div>
<button onClick={this.clickhandle}>点我</button>
</div>)
}
}
export default App;
为什么呢?
函数的this会因为赋值,或者函数作为参数传递(隐式赋值),丢失this绑定。
看个例子:
let my_obj = {
name:'bar',
doSome:function(){
console.log(this)
}
}
let get_obj = my_obj.doSome
get_obj() //Window
上面的例子,通过把函数赋值给一个变量来指向,this指向变量运行时的作用域了。
所以onClick={this.clickhandle} 也是一样的道理,通过赋值给onClick 由onclick调用时的this不是指向该组件;
而且上面的代码使用的是class类,在类声明和类表达式的主体以严格模式执行。
this默认undefined会给开发带来一些问题,比如说需要组件的state,props就无法获取了;所以我们要改变this的指向:
第一种:在constructor函数里面 使用this.clickhandle = this.clickhandle.bind(this) 来改变this的指向:
class App extends React.Component {
constructor(){
super()
this.clickhandle = this.clickhandle.bind(this)
}
clickhandle(){
console.log(this)
}
render() {
return (<div>
<button onClick={this.clickhandle}>点我</button>
</div>)
}
}
export default App;
第二种:在回调函数里面使用this.clickhandle.bind(this) :
class App extends React.Component {
clickhandle(){
console.log(this)
}
render() {
return (<div>
<button onClick={this.clickhandle.bind(this)}>点我</button>
</div>)
}
}
第三种:使用箭头函数 :
class App extends React.Component {
clickhandle=()=>{
console.log(this)
}
render() {
return (<div>
<button onClick={this.clickhandle}>点我</button>
</div>)
}
}
export default App;
箭头函数本身没有绑定this,而是使用定义时所在作用域的this。