简体   繁体   English

为什么扩展React.Component内的方法语法不同?

[英]Why are there different syntax of methods inside extending React.Component?

I notice that inside class ExampleComponent extends React.Component {...} there are different ways of defining methods, with the former being a declaration for methods that is part of React and the latter being expressions for your own methods. 我注意到,在class ExampleComponent extends React.Component {...}内部class ExampleComponent extends React.Component {...}时候,方法的定义方式不同,前者是React一部分的方法声明,后者是您自己方法的表达式。 Why is this? 为什么是这样? Why aren't they both in the same format? 他们为什么不采用相同的格式?

  componentDidMount() {
    ...
  }

vs.

  myMethod = () => {
    ...
  }

This one goes to prototype 这是原型

fnProto() {

}

This one is experimental and goes directly to instance having this always refering to the instance. 这是实验性的,直接进入实例, this实例始终引用实例。

fnInstance = () => {}

Translating to ES5 转换为ES5

class Cmp {
 fnProto() {
   console.log('goes to proto')
 }

  fnInstance = () => {
    console.log('goes to instance')
  }
}

Will be roughly equivalent to 大致相当于

function Cmp() {
   this.fnInstance = (function() {
      console.log('goes to instance')
   }).bind(this)
}

Cmp.prototype.fnProto = function() {
   console.log('goes to proto')
}

When you have 当你有

componentDidMount() {
    ...
  }

it is a lifecycle function and this inside it is automatically bound by default to the React Component context. 它是生命周期功能和this内部会自动默认到阵营组件上下文约束。

However when you define your own function, this inside it will refer to the content of the function itself. 但是,当您定义自己的函数时, this内部将引用函数本身的内容。 However if you define it using an arrow function like 但是,如果使用arrow function定义它,例如

myMethod = () => {
    ...
  }

this keyword inside it will refer to the parent context which in this case is the React Component context. this里面的this关键字将引用父上下文,在这种情况下,它是React Component上下文。

Check this article on Arrow function 查看有关箭头功能的本文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM