在组件内部要渲染的内容上注册事件,由于this.fn属于一个整体,函数fn调用之后指向window,但是是在js文件中所以没有this,所以指向underfined。

class App extends React.Component {
  // constructor(props){
  //   super(props)
  // }
  render() {
    return <button onClick={this.fn}>点击触发事件</button>
  }
  fn() {
    console.log(this); //点击之后打印出underfined
  }
}

解决方案

通过bind方法

  1. 在注册点击事件的时候给他设置bind方法,让他强行指向class生成的实例

     return <button onClick={this.fn.bind(this)}>点击触发事件</button>
  2. 在class的constructor里面强行设置fn函数的指向

    this.fn = this.fn.bind(this)

    属性初始化语法

    注册fn的时候使用箭头函数,箭头函数没有固定的指向,如果自己找不到就自动找上一级

     fn = ()=> {
     console.log(this); 
      }

绑定事件时用箭头函数

onClick={ () => this.fn()  }
Last modification:September 24, 2019
If you think my article is useful to you, please feel free to appreciate