类的方法默认不会绑定this,因此在调用的时候如果忘记绑定,this的值将会是undefined。所以需要手动绑定事件。React中给元素绑定事件,主要有以下几种方式

构造器使用bind绑定this

  1. import React, {Component} from 'react';
  2. class Button extends React.Component {
  3. //构造器 render函数 组件生命周期可以获取到组件实例对象也就是this
  4. constructor(props) {
  5. super(props);
  6. this.handleClick = this.handleClick.bind(this);
  7. /*
  8. 左侧this.handleClick是给组件实例对象上挂载一个属性
  9. 右侧this.handleClick.bind(this)
  10. 先通过__proto__获取原型对象的handleClick方法,再将其binding到this上
  11. 二者结合,就将右侧找到的方法挂载到组件实例对象上了
  12. */
  13. }
  14. handleClick(){ //给Button类添加自定义事件,handleClick函数只能在类的原型对象上
  15. console.log('this is:', this);
  16. }
  17. render() {
  18. return (
  19. <button onClick={this.handleClick}>Click me</button>
  20. //当然 这个binding还可以写在JSX中 在调用的时候同时binding
  21. <button onClick={this.handleClick.bind(this)}>Click me</button>
  22. );
  23. }
  24. }

绑定箭头函数,执行时通过this调用事件

  1. import React, {Component} from 'react';
  2. class Button extends React.Component {
  3. handleClick(){
  4. console.log('this is:', this);
  5. }
  6. render() {
  7. return (
  8. //点击事件绑定的是箭头函数,箭头函数在执行的时候已经可以访问this 直接通过this调用
  9. <button onClick={()=>this.handleClick()}>Click me</button>
  10. );
  11. }
  12. }

属性初始化语句绑定this

  1. import React, {Component} from 'react';
  2. class Button extends React.Component {
  3. //给Button组件初始化一个属性handleClick,值为箭头函数
  4. //箭头函数没有自己的this,在执行时候找外部也就是render函数的this,也就是组件实例对象
  5. handleClick=()=>{
  6. console.log('this is:', this);
  7. }
  8. render() {
  9. return (
  10. <button onClick={this.handleClick}>Click me</button>
  11. );
  12. }
  13. }