LoginSignup
0
0

More than 3 years have passed since last update.

(转)React事件处理函数必须使用bind(this)的原因

Posted at

1.JavaScript自身特性说明
如果传递一个函数名给一个变量,之后通过函数名()的方式进行调用,在方法内部如果使用this则this的指向会丢失。
示例代码:
首先我们创建test对象并直接调用方法 :

const test = {
name:'jack',
getName:function(){
console.log(this.name)
}
}
test.getName()
1
2
3
4
5
6
7
使用node test.js执行上述代码可以正常输出jack。
之后,我们对代码进行调整:

const test = {
name:'jack',
getJack:function(){
console.log(this.name)
}
}
const func = test.getJack;
func();
1
2
3
4
5
6
7
8
我们没有直接调用对象的方法,而是将方法声明给一个中间变量,之后利用中间变量()调用方法,此时this则失去指向,输出undefined,如果使用node环境执行js文件则输出node相关信息,如嵌入到html中则this指向window对象。

2.React事件绑定
React中的bind同上方原理一致,在JSX中传递的事件不是一个字符串,而是一个函数(如:onClick={this.handleClick}),此时onClick即是中间变量,所以处理函数中的this指向会丢失。解决这个问题就是给调用函数时bind(this),从而使得无论事件处理函数如何传递,this指向都是当前实例化对象。
当然,如果不想使用bind(this),我们可以在声明函数时使用箭头函数将函数内容返回给一个变量,并在调用时直接使用this.变量名即可。示例代码如下:

import React from 'react';
export default class Life extends React.Component{
constructor(props){
super(props);
this.state = {
count:4
};
}
render(){
var style = {
padding:'10px',
color:'red',
fontSize:'30px'
}
return (

{/注意js语法使用一个括号{}去表示,style使用两个括号,原因里面其实是一个对象/}

React生命周期介绍


无bind点击一下
有bind点击一下

{this.state.count}



)
}
//此时this指向是当前实例对象
handleAdd = ()=> {
console.log(this)
this.setState({
count:5
})
}
handleClick(){
this.setState({
count:6
})
}

}

版权声明:本文为CSDN博主「汪喆_Jack」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34829447/article/details/81705977

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0