当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React.js绑定this的5种方法(小结)

React.js绑定this的5种方法(小结)

2018年08月12日  | 移动技术网IT编程  | 我要评论
this在javascript中已经相当灵活,把它放到react中给我们的选择就更加困惑了。下面一起来看看react this的5种绑定方法。 1.使用react.c

this在javascript中已经相当灵活,把它放到react中给我们的选择就更加困惑了。下面一起来看看react this的5种绑定方法。

1.使用react.createclass

如果你使用的是react 15及以下的版本,你可能使用过react.createclass函数来创建一个组件。你在里面创建的所有函数的this将会自动绑定到组件上。

const app = react.createclass({
 handleclick() {
  console.log('this > ', this); // this 指向app组件本身
 },
 render() {
  return (
   <div onclick={this.handleclick}>test</div>
  );
 }
});

但是需要注意随着react 16版本的发布官方已经将改方法从react中移除

2.render方法中使用bind

如果你使用react.component创建一个组件,在其中给某个组件/元素一个onclick属性,它现在并会自定绑定其this到当前组件,解决这个问题的方法是在事件函数后使用.bing(this)将this绑定到当前组件中。

class app extends react.component {
 handleclick() {
  console.log('this > ', this);
 }
 render() {
  return (
   <div onclick={this.handleclick.bind(this)}>test</div>
  )
 }
}

这种方法很简单,可能是大多数初学开发者在遇到问题后采用的一种方式。然后由于组件每次执行render将会重新分配函数这将会影响性能。特别是在你做了一些性能优化之后,它会破坏purecomponent性能。不推荐使用

3.render方法中使用箭头函数

这种方法使用了es6的上下文绑定来让this指向当前组件,但是它同第2种存在着相同的性能问题,不推荐使用

class app extends react.component {
 handleclick() {
  console.log('this > ', this);
 }
 render() {
  return (
   <div onclick={e => this.handleclick(e)}>test</div>
  )
 }
}

下面的方法可以避免这些麻烦,同时也没有太多额外的麻烦。

4.构造函数中bind

为了避免在render中绑定this引发可能的性能问题,我们可以在constructor中预先进行绑定。

class app extends react.component {
 constructor(props) {
  super(props);
  this.handleclick = this.handleclick.bind(this);
 }
 handleclick() {
  console.log('this > ', this);
 }
 render() {
  return (
   <div onclick={this.handleclick}>test</div>
  )
 }
}

然后这种方法很明显在可读性和维护性上没有第2种和第3种有优势,但是第2种和第3种由于存在潜在的性能问题不推荐使用,那么现在推荐 ecma stage-2 所提供的箭头函数绑定。

5.在定义阶段使用箭头函数绑定

要使用这个功能,需要在.babelrc种开启stage-2功能,绑定方法如下:

class app extends react.component {
 constructor(props) {
  super(props);
 }
 handleclick = () => {
  console.log('this > ', this);
 }
 render() {
  return (
   <div onclick={this.handleclick}>test</div>
  )
 }
}

这种方法有很多优化:

  1. 箭头函数会自动绑定到当前组件的作用域种,不会被call改变
  2. 它避免了第2种和第3种的可能潜在的性能问题
  3. 它避免了第4种绑定时大量重复的代码

总结:

如果你使用es6和react 16以上的版本,最佳实践是使用第5种方法来绑定this

参考资料:

react.js pure render性能渲染反模式

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网