在react組件中,每一個方法的上下文都會指向該組件的實例,即自動綁定this爲當前組件,並且react還會對這種引用進行緩存,以達到cpu和內存的最大化。在使用了es6 class或者純函數時,這種自動綁定就不復存在了,咱們須要手動實現this的綁定
如下是幾種綁定的方法:react
bind方法
直接綁定是bind(this)來綁定,可是這樣帶來的問題是每一次渲染是都會從新綁定一次bind;es6
class Home extends React.Component { constructor(props) { super(props); this.state = { }; } del(){ console.log('del') } render() { return ( <div className="home"> <span onClick={this.del.bind(this)}></span> </div> ); } }
構造函數內綁定
在構造函數 constructor 內綁定this,好處是僅須要綁定一次,避免每次渲染時都要從新綁定,函數在別處複用時也無需再次綁定緩存
class Home extends React.Component { constructor(props) { super(props); this.state = { }; this.del=this.del.bind(this) } del(){ console.log('del') } render() { return ( <div className="home"> <span onClick={this.del}></span> </div> ); } }
::不能傳參
若是不傳參數使用雙冒號也是能夠函數
class Home extends React.Component { constructor(props) { super(props); this.state = { }; } del(){ console.log('del') } render() { return ( <div className="home"> <span onClick={::this.del}></span> </div> ); } }
箭頭函數綁定
箭頭函數不只是函數的'語法糖',它還自動綁定了定義此函數做用域的this,由於咱們不須要再對它們進行bind方法:this
class Home extends React.Component { constructor(props) { super(props); this.state = { }; } del=()=>{ console.log('del') } render() { return ( <div className="home"> <span onClick={this.del}></span> </div> ); } }
以上幾種方法均可以實現this綁定,使用那種各自的習慣;
但願你們喜歡,也但願你們指點錯誤,也能夠加入qq羣439667347,你們一塊兒討論,一塊兒進步,後續更新中...spa