React类的方法绑定 this 的方式

Posted samve

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
    );
  }
}
技术图片

以上是关于React类的方法绑定 this 的方式的主要内容,如果未能解决你的问题,请参考以下文章

React-事件绑定

react系列-事件绑定的几种方法对比

无法比较包含绑定到我在 React 中的类的函数的对象

react类方法的绑定

React--事件处理

React绑定事件this指向问题--改变state中的值