react 中 事件函数写法与this 指向总结
—个人学习总结,如果有写得不对的地方,欢迎大家指正
Class App extends Component{
constructor(props){
super(props);
this.state = {
username: ‘blue’,
pwd: ‘kkk’
}
}
render(){
const { username, pwd } = this.state;
return(
<input value={username} onChange = { this.handleChange }>
// onChange 事件 { this.handleChange };react 中写法 不要加()执行;
handleChange (){
alert(“this:”,this);//undefined
this.setState({username: ‘jack’})
}
}
// 分析:首先我们知道,onChange = { this.handleChange } 括号内的环境是该组件,那为什么触发onChaneg事件时,handleChange函数的调用对象却是undefined了?
我们知道,普通函数中this是指向 调用该函数的对象,而onChange、onClick这些鼠标键盘事件得调用对象是 Window这个顶级对象,不是该component组件调用得,{ this. handleChange }中this指向为该组件,this.handleChange指的组件中的handleChange()函数, 但是handleChange调用对象是window,在react 环境下指向为 undefined; 所以点击时,handleChange函数中的this指向为undefined;
所以为了纠正this的指向,使得this指向该组件,有以下解决方法:
法一:bind 绑定this 指向
写法有二:–一、 onChange = { this.handleChaneg.bind(this) }
分析:
首先我们知道,普通函数中this是指向 调用该函数的对象,所以只要把handleChaneg函数绑定到该组件App环境下,那么函数中this就指向该组件App了,这里{} 内环境是App组件,所以bind(this),就是把该函数绑定到App组件内,所以函数内部的this指向就明确了,指向App组件;
二、onChange = { this.handleChange },然后在constructor中绑定this;
constructor(props){
super(props);
this.state = {
username: ‘blue’,
pwd: ‘kkk’
}
this.handlechange = this.handlechange.bind(this);
}
法二: 把onChange 中 函数写成箭头函数
onChange = {()=> { this.handleChange() } }因为箭头函数内部this指向定义该函数时父级的环境,也就是input 标签所处的环境,也就是该App组件;
法三: 把handleChange这个函数体写成箭头函数的形式
onChange = { this.handleChange }
handleChange = ()=>{
alert(“this:”,this);//App组件
this.setState({username: ‘jack’})
}
handleChange 函数内this指向定义该函数时父级所处的环境,也就是App组件;