React函數調用方式,以及坑


React函數調用方式,以及坑

結構學AI
0.1822017.03.15 11:45:50字數 160閱讀 9,950

好吧這篇文章沒想到看得人這么多....出乎意料,mark下,改天寫篇原理吧,另外下面是去年在鵝廠的寫法,后面鵝廠就不能用react了...
急用的看最后兩個就好了,其他情況沒啥營養的,就是試錯

情況一:

constructor(props) { super(props); this.login = this.login.bind(this); } login(a,b,c) { console.log(this);//打印這個組件本身 console.log(a);//打印111111 console.log(b);//undefined console.log(c);//undefined } <button onClick={()=>{this.login(111111)}} /> 

情況二:

constructor(props) { super(props); this.login = this.login.bind(this); } login(a,b,c) { console.log(this);//打印這個組件本身 console.log(a);//打印Proxy對象:Proxy里面可以獲得dom元素 console.log(b);//打印event console.log(c);//undefined } <button onClick={this.login} /> 

情況三:

constructor(props) { super(props); // this.login = this.login.bind(this); } login(a,b,c) { console.log(this);//打印這個組件本身,說明我們用箭頭函數的時候,不需要bind(this),react自動把this指向了組件自己, console.log(a);//打印出了111111 console.log(b);//undefined console.log(c);//undefined } <button onClick={()=>{this.login(111111)}} /> 

情況四:

constructor(props) { super(props); // this.login = this.login.bind(this); } login(a,b,c) { console.log(this);//打印null,這是react最常見的坑,this本來指向window,但是經過react初始化之后,指向了null; console.log(a);//打印Proxy對象:Proxy里面可以獲得dom元素 console.log(b);//打印event console.log(c); } <button onClick={this.login} /> 

情況五:

constructor(props) { super(props); // this.login = this.login.bind(this); } login(a,b,c) { console.log(this);//打印這個組件本身 console.log(a);//undefined console.log(b);//undefined console.log(c);//undefined } <button onClick={()=>{this.login()}} /> 

情況六:(可以算作es5的最佳實踐,用的es5的方法,拿到所有參數)

constructor(props) { super(props); // this.login = this.login.bind(this); this.login=(a,b,c)=>{ console.log(this);//打印這個組件本身 console.log(a);//111111 console.log(b);//打印Proxy對象:Proxy里面可以獲得dom元素 console.log(c);//打印event: } } <button onClick={this.login.bind(this,111111)} /> 

最佳實踐:(for es6) 老版本

constructor(props) { super(props); // this.login = this.login.bind(this); } login(type,event,proxy) { console.log(this);//打印這個組件本身 console.log(event);//打印event: console.log(proxy);//打印Proxy對象,event詳情請查驗es6 } <button onClick={()=>{let target=this, handler={};this.login('boss',event,new Proxy(target, handler))}}/> 

最佳實踐:2018(需要傳參)

constructor(props) { super(props); } login=(num, evt)=>{ console.log(num);//打印傳參 console.log(evt);//打印event: } <button onChange={this.login.bind(null, 111)}/> 

最佳實踐:2018(不需要傳參)

constructor(props) { super(props); } login=( evt)=>{ console.log(evt);//打印event: } <button onChange={this.login}/>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM