react里面的this指向问题

才学react几天 求问大神react的this问题


class App extends React.Component {
  // constructor(props){
  //   super(props)
  // }
  state={
    name:'ls'
  }
  render() {
    return <button onClick={ this.fn }>点击触发事件</button>
  }
  fn() {
    console.log(1);
    console.log(this);
  }
}

为什么点击之后这里的this是打印的undefined 而不是这个实例

我知道4个解决办法 但是我就是搞不懂为什么this指向的undefined
按理说这里this.fn触发了 不就是对象里面方法的调用吗 既然这样 方法里面的this不就是指向这个对象的吗
为什么会是undefined
听大佬说 这个this指的是点击这个事件 所以是undefined

那我用箭头函数为什么就又可以了(箭头函数没有this,this会不断往上作用域链寻找)


class App extends React.Component {
  // constructor(props){
  //   super(props)
  // }
  state={
    name:'ls'
  }
  render() {
    return <button onClick={ this.fn }>点击触发事件</button>
  }
 
  fn = ()=>{
  console.log(1);
  console.log(this);
   }
}
阅读 4.2k
2 个回答

你要在constructor里把fn里的this指向绑定到这个组件。
还有state写到constructor函数里

class App extends React.Component {
   constructor(props){
     super(props);
     this.state = {}
     //这里绑定,这样fn函数里的this就指向这个组件
     this.fn = this.fn.bind(this);
   }
  
  fn(){
    console.log(this);
  }

  render() {
    return <button onClick={ this.fn }>点击触发事件</button>
  }
  
}

这是由 JavaScript 本身产生的问题

首先, class 的本质是基于原型的 prototype

当你定义方法的时候使用箭头函数,这个时候 this 的指向已经确定好了,就是指向 App,所有调用不会有问题

然而, 当你定义方法的时候使用 fn(){} 这种方式就相当于

App.prototype.fn = function(){}

这个函数只有在调用的时候才能确定 this 的 指向,所以在 onClick 调用 fn 函数的时候,默认情况下,this 是指向全局的。但是,在 class 中默认使用严格模式,不会默认绑定,所以打印出来的 this 就是 undefined

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题