最近学习React,同时动手写了一个todo。在写这个简单的demo中遇到了一个问题,那就是React类组件中函数绑定需要手动绑定this。为了搞清楚为啥需要这样做,为此我在网上搜索资料结合自己的理解讲述下里面的原因。

bug产生的由来


 class PostItem extends React.Component{
     constructor(props){
         super(props)
     }
    handleClick(e){
        console.log(this); // this的值为undefined
    }
    render(){
        return(
            <button type='button' onClick={this.handleClick}>
             click
            </button>
        )
    }
 }

以上打印结果this的值为undefined

产生的原因

对于产生这种bug的原因主要有两点需要注意的:

  • this的指向
  • render过程中做了什么

React主要是通过React.createElement来模拟document.createElement来创建Dom元素(React创建的是虚拟的Dom树),下面我就通过另一种方法实现上面的代码。

 //创建Dom方法
 function createElement(dom,params){
     let dom = document.createElement(dom)
     dom.onclick = params.onclick;
     dom.innerHTML = 'click'
     document.body.appendChild(dom)
 }

 class Demo {
     handleClick(){
         console.log(this); //this打印button这个dom
     }

     render(){
         createElement('button',{
             onclick:this.handleClick
         })
     }
 }

  new Demo().render();

此时的this结果指向button这个dom元素,出现这个原因是由于在this.handleClick作为callback传递给createElement函数时,this指向即丢失了。最后this.handleClick作为方法传递给dom.onclick,结果指向的就是创建的Dom元素。

除了手动绑定this的其他方案

第一种方式

 class Demo {
     onClick = () =>{

     }
 }

第二种方式

class Demo {
  constructor(props){
         super(props)
     }
    handleClick(e){
        console.log(this); // this的值为undefined
    }
    render(){
        return(
            <button type='button' onClick={ () =>{this.handleClick()}}>
             click
            </button>
        )
    }

}