[译] React 组件中绑定回调

原文:Binding callbacks in React components

在组件中给事件绑定处理函数是很常见的,比如说每当用户点击一个button的时候使用console.log打印一些东西。

class DankButton extends React.Component {  render() {    return Click me!  }  handleClick() {    console.log(`such knowledge`)  }}

很好,这段代码会满足你的需求,那现在如果我想在handleClick()内调用另外一个方法,比如logPhrase()

class DankButton extends React.Component {  render() {    return Click me!  }  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  this.handleClick()}>Click me!  }  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 Click me!  }  handleClick() {    this.logPhrase()  }  logPhrase() {    console.log('such gnawledge')  }}

这个方案和箭头函数有同样的问题,在每次render的时候都会创建一个新的函数,但是为什么没有使用匿名函数也会这样呢,下面就是答案。

function test() {}const testCopy = testconst boundTest = test.bind(this)console.log(testCopy === test) // trueconsole.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 Click me!  }  handleClick() {    this.logPhrase()  }  logPhrase() {    console.log('such gnawledge')  }}

很好,现在我们的函数被绑定到正确的上下文,而且不会在每次渲染的时候创建新的函数。

如果你使用的是React.createClass而不是ES6的classes,你就不会碰到这个问题,createClass生成的组件会把它们的方法自动绑定到组件的this,甚至是你传递给事件回调的函数。

关键字:JavaScript, react.js, 函数, logphrase


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部