react 中 事件函数写法与this 指向总结

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组件;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值