首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >=符号左侧的this.handleClick是做什么的?

=符号左侧的this.handleClick是做什么的?
EN

Stack Overflow用户
提问于 2019-05-15 22:17:08
回答 1查看 75关注 0票数 0

我对如何在ES6构造函数中使用this感到困惑。

首先,我理解了以下内容(参见下面的示例):-我们使用this.height = height;添加一个新的instance variable

  • 使用className() {...}添加一个新的实例方法,并使用getter this添加一个静态类来引用下面的getter中的实例方法,如this.calcArea()

代码语言:javascript
复制
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  get area() {   // Getter
    return this.calcArea();
  }
  calcArea() {
    return this.height * this.width;
  }
  static staticMethod() {
    return 'static method has been called.';
  }
}

然而,当我看到下面附加的React示例时,ln-7中的this.handleClick = this.handleClick.bind(this);让我感到困惑。我理解this.handleClick.bind(this);的意思。我怀疑的部分是this.handleClick,它位于=标志的LEFT一侧。this.handleClick看起来像是在做一个名为handleClick的instance variable。在前面的例子中,我用this.height = height;的b/c的方式来看待它。

我的问题是:我的想法错了吗?或者谁能解释一下=标志的LEFT端的this.handleClick是做什么的?

EN

回答 1

Stack Overflow用户

发布于 2019-05-15 22:27:02

用于将函数绑定到组件实例上。请查看here。它用于ES5函数。如果你使用了ES6函数,你就不需要使用find了。

代码语言:javascript
复制
class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this); // need binding for es5
  }

  handleClick() {
    console.log('Click happened');
  }

  handleClick2 = () => {
    console.log('click happened (es6)');
  }

  render() {
    return (
       <div>
         <button onClick={this.handleClick}>Click Me</button>
         <button onClick={this.handleClick2}>Click Me 2</button>
       </div>
    );
  }
}

注意: this关键字用于在基本javascript类的情况下为对象实例赋值。类似地,它被用于react类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56151531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档