React中的一些困惑——bind(this)

bind(this)

如果你用过React,或者正在用React作开发,就一定看过或者写过这种代码:

	constructor(props){
        super(props)
	    this.handlerEvent = this.handlerEvent.bind(this)
    }
	handlerEvent(){
		//随便写点什么
	}

为什么要在这里有一步bind(this)这种操作?它干了点啥?没有bind会怎么样?

  其实这三个问题可以一并说:首先,我们先把上面的代码改一下:

class Demo {
	constructor(props){
		super(props)
	}
	handlerEvent(){
		console.log(this)//Demo
	}
}

  在不考虑React的前提下,想要调用这个handlerEvent函数那么我们就要
new Demo().handlerEvent(),执行的结果为Demo这个class,这说明调用handlerEvent的是Demo,可是如果把new Demo()赋值给一个变量变成这样:

class Demo {
	constructor(props){
		super(props)
	}
	handlerEvent(){
		console.log(this)//undefined
	}
}
let demo = new Demo().handlerEvent
demo.()

  这里的this就变成了undefined(不是指向window是因为使用class会触发严格模式,所以this就成了undefined)。
  看到这可能你已经有点明白我说了这么多是啥意思了。
当你在React中绑定时间的时候一定会这样写:

	render(){
		<button onClick={this.handlerClick.bind(this)}></button>
	}

通过上面的例子可以知道,如果把一个函数赋值给一个变量,那么它内部的this就会改变指向,这里把handlerClick赋值给onClick的之前就绑定了内部的this(指向实例本身),所以就不会出现this指向错误的问题
当然解决这个问题的办法不止这一种,你可以在声明这个函数的时候就进行bind,也可以在调用处的外层包裹一层箭头函数,也可以在实例化class的时候(在constructor函数中)将经过绑定的函数赋值给当前函数,方法如下:

class Demo extends Component{
//方法1
	constructor(){
		this.fn = this.fn.bind(this)
	}
//方法2
	fn(){
		console.log(this)
	}.bind(this)
}
	arrow(){
		console.log(this)
	}
//方法3
	render(){
		return <button onClick={()=>{this.arrow}}>按钮</button>
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值