Javascript class methods versus properties

后端 未结 2 1691
借酒劲吻你
借酒劲吻你 2021-02-06 01:32

I\'ve seen code using Javascript classes use the following form (example is React):

class UserProfile extends Component {
  state = {
    open: false
  }

  hand         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 01:51

    It's about the context of this inside of your method. If you would implement it like your second example, this won't reference the component instance, using the arrow function like in your first example this references the component instance. (Due to not using React.createClass).

    For your second example you have to do this.handleOpen = this.handleOpen.bind(this) inside your constructor.

    EDIT: For details about arrow functions see the answer from Chris.

提交回复
热议问题