React 绑定事件的几种写法bind(this)

1. 我们在 React class Component 绑定事件时,经常会通过 bind(this) 来绑定事件  

class Home extends React.Component{
  constructor( props ){
    super( props );
  }
  handleClick(event){
    // todo something
  }
  render(){
    return (
      <button type="button" onClick={this.handleClick.bind(this)}>
        Click Me
      </button>
    );
  }
}
或者在构造函数内绑定的写法
class Home extends React.Component{
  constructor( props ){
    super( props );
   this.handleClick = this.handleClick.bind(this) } handleClick(event){ // todo something } render(){ return ( <button type="button" onClick={this.handleClick}> Click Me </button> ); } }

  如果不用bind绑定,this的值为undefined。 因为当button被点击时,会由React作为中介调用回调函数,此时的this指向丢失,就指向了window。

  bind this 的原理:

    new 关键字, 在使用new 关键字时,构造函数(即class)中的this都会强制赋值为新的对象。使用bind将this的值绑定在函数中

  不用bind绑定的方法: 

    最常用的 public class fields  

    因为我们使用 public class fields 语法,handleClick 箭头函数会自动将 this 绑定在 Home 这个class

class Home extends React.Component{
  constructor( props ){
    super( props );
  }
  handleClick = () => {
    // todo something
  }
  render(){
    return (
      <button type="button" onClick={this.handleClick}>
        Click Me
      </button>
    );
  }
}    

    箭头函数

     在ES6中,箭头函数 this 默认指向函数的宿主对象(或者函数所绑定的对象)

class Home extends React.Component{
  constructor( props ){
    super( props );
  }
  handleClick(params){
    // todo something
  }
  render(){
    return (
      <button type="button" onClick={ () => {this.handleClick(params)}>
        Click Me
      </button>
    );
  }
}

  

原文地址:https://www.cnblogs.com/qianxiaoniantianxin/p/14844473.html