[译] React 组件中绑定回调

原文:Binding callbacks in React componentsreact

在组件中给事件绑定处理函数是很常见的,好比说每当用户点击一个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')
  }
}

这样居然不行,会获得以下的错误提醒this

TypeError: this.logPhrase is not a function at handleClick (file.js:36:12)

当咱们把handleClick绑定到 onClick的时候咱们传递的是一个函数的引用,真正调用handleClick的是事件处理系统。所以handleClickthis上下文和我门想象的this.logPhrase()是不同的。code

这里有一些方法可让this指向DankButton组件。component

很差的方案 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)

另一个解决这个问题的方案是,把回调绑定到正确的上下问thisget

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的时候都会建立一个新的函数,可是为何没有使用匿名函数也会这样呢,下面就是答案。it

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,甚至是你传递给事件回调的函数。

相关文章
相关标签/搜索