React类的方法绑定 this 的方式

一、在constructor中bind绑定组件的this:

class Button extends React.Component{
  constructor(pops){
    super();
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick = () => {
    console.log("this is ", this);
  }

  render(){
    return (<button onClick={this.handleClick}>按钮</button>)
  }
}

二、方法使用时绑定 this:

class Button extends React.Component{
  constructor(props){
    super(props);
  }

  handleClick = () => {
    console.log("this is ", this);
  }

  render(){
    return (<button onClick={this.handleClick.bind(this)}>按钮</button>)
  }
}

ReactDOM.render(
  <Button/>,
  document.getElementById("app")
);

三、使用属性初始化语法:

class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

四、在回调函数中使用 箭头函数:

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}
posted @ 2020-03-01 21:13  Samve  阅读(442)  评论(0编辑  收藏  举报