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> ) } }
这种方法有很多优化:
- 箭头函数会自动绑定到当前组件的作用域种,不会被call改变
- 它避免了第2种和第3种的可能潜在的性能问题
- 它避免了第4种绑定时大量重复的代码
总结:
如果你使用ES6和React 16以上的版本,最佳实践是使用第5种方法来绑定this
参考资料:
React.js pure render性能渲染反模式
this绑定装饰器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 群星.1991-不一样的感觉REMIX【宝丽金】【WAV+CUE】
- 银霞.1983-《你那好冷的小手》珍藏纪念版[WAV分轨]
- 银霞.2002-《国语巨星专辑VOL.3》2CD台湾版[WAV+CUE]
- 金池刘罡《昨日情歌HQ》头版限量编号[低速原抓WAV+CUE]
- 段奥娟.2024-23·岁碎念【白米范】【FLAC分轨】
- 顺子.2001-昨日·唯一·更多·顺子自选辑【魔岩】【WAV+CUE】
- 无印良品.1999-私藏三首·原创相对论(EP)【滚石】【WAV+CUE】
- Merryland《Merryland》[FLAC/分轨][170.22MB]
- 庄锭欣 ELKIE《没有你的未来》[320K/MP3][15.78MB]
- 庄锭欣 ELKIE《没有你的未来》[FLAC/分轨][36MB]
- TchaikovskySwanLake,Op.20柴可夫斯基天鹅湖(2013)SACD[Hi-Res]
- 24bit达人艺典《琴歌终极版》整轨WAV+CUE
- 黑鸭子.2005-《发烧DSD》柏菲[WAV分轨]
- 群星.1990-电影看板·人间道【宝丽金】【WAV+CUE】
- 周殷廷.2024-TO.WHOM.IT.MAY.CONCERN【环球】【FLAC分轨】