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