为什么需要在构造函数中绑定函数 [英] why do you need to bind a function in a constructor

查看:36
本文介绍了为什么需要在构造函数中绑定函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此代码相关的问题:https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js

I have a question relavent to this code: https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js

特别是:

  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    this.handleRefreshClick = this.handleRefreshClick.bind(this)
  }

我想这是一个由两部分组成的问题.

I guess its a 2 part question.

  1. 为什么我需要将handle change设置为this.handleChange =类的一个实例,我不能只使用handleChange的静态函数并在onClick类中直接调用它={handleRefreshClick}> ?
  2. 我不知道这里发生了什么:this.handleRefreshClick.bind(this)
  1. Why do I need to set handle change as an instance of class this.handleChange =, can't I just use static functions for handleChange and call it directly with in the class onClick={handleRefreshClick}> ?
  2. I have no idea whats going on here: this.handleRefreshClick.bind(this)

谢谢

推荐答案

反序回答...

  1. this.handleRefreshClick.bind(something) 返回一个新函数,其中对 this 的引用将引用 something.这是一种保存this的当前值的方式,它在调用构造函数的时候就在作用域内,以便以后调用函数时可以使用.
  1. this.handleRefreshClick.bind(something) returns a new function, in which references to this will refer to something. This is a way of saving the current value of this, which is in scope during the call to the constructor, so that it can be used later when the function is called.

  1. 如果您的函数不需要访问组件的状态,那么当然,您不需要绑定它们.

<小时>

支持将这些行添加到构造函数的论点是,新的绑定函数仅在每个类实例中创建一次.你也可以使用


The argument in favour of adding these lines to the constructor is so that the new bound functions are only created once per instance of the class. You could also use

onClick={this.handleRefreshClick.bind(this)}

或(ES6):

onClick={() => this.handleRefreshClick()}

但是每次重新渲染组件时,这两种方法中的任何一种都会创建一个新函数.

but either of these methods will create a new function every time the component is re-rendered.

这篇关于为什么需要在构造函数中绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆