美文网首页
react中this指向问题

react中this指向问题

作者: cutecat | 来源:发表于2017-03-09 17:01 被阅读0次

一.不对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) }}

相关文章

  • react中this指向问题

    一.不对this指向做任何改变 class Btn extends React.Component{ rend...

  • React 中 this指向问题

    在写react mobx的demo时,给checkbox 添加一个onChange事件,并且忘记在construc...

  • React this 指向问题

    React this 指向问题 在 Class 里面使用, this.setState()报错: Cannot r...

  • react: React.forwardRef

    关键点就是React.forwardRef的API中ref必须指向dom元素而不是React组件。 一、React...

  • this指向以及react中绑定this

    JavaScript函数中的this 我们都知道JavaScript函数中的this不是在函数声明的时候定义的,而...

  • 浅谈react 中的 this 指向

    前言 最近在做一个项目的时候 关于class方法中 this 指向以及 外置prototype 的 this 指向...

  • JavaScript中This指向问题

    1 全局作用域或者普通函数的this指向Windows //直接打印console.log(this) //win...

  • js中this指向问题

    this的指向在函数定义的时候是无法确定的,只有函数执行的时候才能确定this到底指向谁,实际this指向是调用他...

  • javascript中this指向问题

    正确理解了this,才算是迈入了JavaScript这门语言JavaScript特性 由于在运行时绑定的特性,js...

  • JavaScript中this指向问题

    直接调用 即为通过函数名()调用,这是,函数内部的this指向全局变量,在浏览器中全局对象是window,在nod...

网友评论

      本文标题:react中this指向问题

      本文链接:https://www.haomeiwen.com/subject/fsawgttx.html