react中this指向问题

2017-03-09  本文已影响0人  cutecat

一.不对this指向做任何改变

class Btn extends React.Component{

     render() {      

          return(<button onClick={this.press()}>开关</button> )

    }

     press(){console.log(this)}

}      

ReactDOM.render( <Btn/>,document.getElementById('example')      );

this.press()的this指向当前作用域Btn,而react内部return是执行了React.createElement这个button按钮,因此改变了原本指向windows的this的指向,因此当前环境下是指向undefined,如果return的不是DOM的标签而是另外的组件比如CustomButton,那么this指向的就会是这个另外的组件CustomButton的作用域

二。将当前环境的this绑定在单纯press函数上

onClick={this.press().bind(this)}  这里的this都是Btn作用域,因此press函数内部的this指向也是Btn作用域

也相当于onClick= {function(){console.log(this)}.bind(this)}

三。使用ES6箭头函数书写press函数

onClick={this.press()}

press = () => {console.log(this)}

箭头函数在书写上等同于匿名函数press=function(){},但是实际上箭头函数默认已经将当前作用域绑定了,因此onClick不用bind(this),press函数里面的this指向就已经指向了Btn作用域

也等同于onClick={() => { console.log(this) }}

上一篇 下一篇

猜你喜欢

热点阅读