在react組件中,每個方法的上下文都會指向該組件的實例,即自動綁定this為當前組件,而且react還會對這種引用進行緩存,以達到cpu和內存的最大化。在使用了es6 class或者純函數時,這種自動綁定就不復存在了,我們需要手動實現this的綁定
React事件綁定類似于DOM事件綁定,區別如下:
1.React事件的用駝峰法命名,DOM事件事件命名是小寫
2.通過jsx,傳遞一個函數作為event handler,而不是一個字符串。
3.React事件不能通過返回false來阻止默認事件,需要顯式調用preventDefault()
如下實例:
<a href="#" onclick="console.log('The link was clicked.'); return false">Click me</a>class ActionLink extends React.Component {constructor(props) {super(props);}handleClick(e) {e.preventDefault();console.log('The link was clicked.');}render() {return (<a href="#" onClick={this.handleClick.bind(this)}>Click Me...</a>);}}ps:React組件類的方法沒有默認綁定this到組件實例,需要手動綁定。
以下是幾種綁定的方法:
bind方法
直接綁定是bind(this)來綁定,但是這樣帶來的問題是每一次渲染是都會重新綁定一次bind;
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方法:
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綁定,使用那種各自的習慣;希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答