原文:Binding callbacks in React components
在组件中给事件绑定处理函数是很常见的,比如说每当用户点击一个button的时候使用console.log 打印一些东西。
class DankButton extends React.Component {
render() {
return <button onClick={this.handleClick}>Click me!</button>
}
handleClick() {
console.log(`such knowledge`)
}
}
很好,这段代码会满足你的需求,那现在如果我想在handleClick() 内调用另外一个方法,比如logPhrase()
class DankButton extends React.Component {
render() {
return <button onClick={this.handleClick}>Click me!</button>
}
handleClick() {
this.logPhrase()
}
logPhrase() {
console.log('such gnawledge')
}
}
这样竟然不行,会得到如下的错误提醒
TypeError: this.logPhrase is not a function at handleClick (file.js:36:12)
当我们把handleClick 绑定到 onClick 的时候我们传递的是一个函数的引用,真正调用handleClick 的是事件处理系统。因此handleClick 的this 上下文和我门想象的this.logPhrase() 是不一样的。
这里有一些方法可以让this 指向DankButton组件。
不好的方案 1:箭头函数
箭头函数是在ES6中引入的,是一个写匿名函数比较简洁的方式,它不仅仅是包装匿名函数的语法糖,箭头函数没有自己的上下问,它会使用被定义的时候的this 作为上下文,我们可以利用这个特性,给onClick 绑定一个箭头函数。
class DankButton extends React.Component {
render() {
// Bad Solution: An arrow function!
return <button onClick={() => this.handleClick()}>Click me!</button>
}
handleClick() {
this.logPhrase()
}
logPhrase() {
console.log('such gnawledge')
}
}
然而,我并不推荐这种解决方式,因为箭头函数定义在render 内部,组件每次重新渲染都会创建一个新的箭头函数,在React中渲染是很快捷的,所以重新渲染会经常发生,这就意味着前面渲染中产生的函数会堆在内存中,强制垃圾回收机制清空它们,这是很花费性能的。
不好的方案 2:this.handleClick.bind(this)
另外一个解决这个问题的方案是,把回调绑定到正确的上下问this
class DankButton extends React.Component {
render() {
// Bad Solution: Bind that callback!
return <button onClick={this.handleClick.bind(this)}>Click me!</button>
}
handleClick() {
this.logPhrase()
}
logPhrase() {
console.log('such gnawledge')
}
}
这个方案和箭头函数有同样的问题,在每次render 的时候都会创建一个新的函数,但是为什么没有使用匿名函数也会这样呢,下面就是答案。
function test() {}
const testCopy = test
const boundTest = test.bind(this)
console.log(testCopy === test) // true
console.log(boundTest === test) // false
.bind 并不修改原有函数,它只会返回一个指定执行上下文的新函数(boundTest和test并不相等),因此垃圾回收系统仍然需要回收你之前绑定的回调。
好的方案:在构造函数(constructor)中bind handleClick
仍然使用 .bind ,现在我们只要绕过每次渲染都要生成新的函数的问题就可以了。我们可以通过只在构造函数中绑定回调的上下问来解决这个问题,因为构造函数只会调用一次,而不是每次渲染都调用。这意味着我们没有生成一堆函数然后让垃圾回收系统清除它们。
class DankButton extends React.Component {
constructor() {
super()
// Good Solution: Bind it in here!
this.handleClick = this.handleClick.bind(this)
}
render() {
return <button onClick={this.handleClick}>Click me!</button>
}
handleClick() {
this.logPhrase()
}
logPhrase() {
console.log('such gnawledge')
}
}
很好,现在我们的函数被绑定到正确的上下文,而且不会在每次渲染的时候创建新的函数。
如果你使用的是React.createClass 而不是ES6的classes,你就不会碰到这个问题,createClass 生成的组件会把它们的方法自动绑定到组件的this ,甚至是你传递给事件回调的函数。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|