reactreact中的this

10次阅读

共计 829 个字符,预计需要花费 3 分钟才能阅读完成。

class App extends React.Component{constructor(props) {super(props);
    // 为了使 this 指向当前类
    // this.handleClick = this.handleClick.bind(this);
  }
  
  // 测试函数
  handler() {console.log(`handler 被调用,this 指向:`,this);
  }
 
  render(){
    return(
        <div>
          <h1>hello World</h1>
            <label htmlFor = 'btn'> 单击打印函数 handler 中 this 的指向 </label>
            <input id = "btn" type="button" value = '单击' onClick = {this.handler}/>
       </div>        
   )
 }
} 

输出“handler 被调用,this 指向 : undefined”,因为这里的 this 只是为 click 事件指定回调函数,只有在事件触发是才调用这个函数,此时在 click 合成函数里无法明确是谁调用了这个函数 (所以 this 具不确定性为 undefined,此时使用 this.setState 会报错)

自动绑定和手动绑定

  • React.createClass 可以自动绑定所以方法的 this 到组件实例,其他 ES6 类语法不会绑定 this 环境,所以需要手动绑定
  • 所以我们通常在 constructor 中绑定方法的 this 指向

总结

  • react 组件生命周期函数里 this 指向组件实例
  • 自定义组件函数中的 this 会因为调用者不同而不同
  • 为了在组件函数中获取组件实例,需要手动绑定 this 到组件实例

    • 在 constructor 函数里 this.handleClick = this.handleClick.bind(this);
    • 在绑定事件时绑定 this <div onClick = {this.handler.bind(this)} >
    • 使用箭头函数定义方法 <div onClick = {() => this.handler()} >
    • 使用 ES7 的 ::
正文完
 0