JavaScript / React中的bind()

时间:2019-06-04 13:20:37

标签: javascript reactjs react-native

为什么需要在构造函数内部绑定()函数?

constructor (props){
    super(props);
    this.funcao = this.funcao.bind(this);
}

不使用构造函数就无法绑定()吗?

3 个答案:

答案 0 :(得分:1)

请记住,如果您在类中将函数编写为箭头函数,则无需绑定(this)..它是自动的。您不需要在构造函数中绑定属性,因为它已经附加了this关键字。

答案 1 :(得分:1)

您不必在构造函数中绑定方法,请看下面的解释。

// Setup (mock)
class MyValue {
  constructor(value) {
    this.value = value;
  }

  log() {
    console.log(this.value);
  }
  
  bindMethods() {
    this.log = this.log.bind(this);
  }
}
const value = new MyValue("Hello World!");
var onclick;

// Explanation

console.log("==== 1. ====");
// Normally when you call a function, you call it with
// a receiver. Meaning that it is called upon an object.
// The receiver is used to fill the `this` keyword.
//
//     «receiver».«method name»(«params»)
//
value.log();
// In the line above `value` is the receiver and is used
// when you reference `this` in the `log` function.

console.log("==== 2. ====");
// However in React a function is often provided to an
// handler. For example:
//
//     onclick={this.log}
//
// This could be compared to the following:
onclick = value.log;
// When the event is triggered the function is executed.
try {
  onclick();
} catch (error) {
  console.error(error.message);
}
// The above throws an error because the function is 
// called without receiver. Meaning that `this` is
// `undefined`.

console.log("==== 3. ====");
// Binding a function pre-fills the `this` keywords.
// Allowing you to call the function without receiver.
onclick = value.log.bind(value);
onclick();

console.log("==== 4. ====");
// Another option is using an anonymous function to
// call the function with receiver.
onclick = () => value.log();
onclick();

console.log("==== 5. ====");
// Binding doesn't have to occur in the constructor,
// this can also be done by any other instance function.
// a.k.a. a method.
value.bindMethods();
// After binding the functions to the receiver you're
// able to call the method without receiver. (Since all
// `this` keywords are pre-filled.)
onclick = value.log;
onclick();

有关this关键字的更多详细信息,您应该浏览MDN this documentation

不必使用this关键字的方法就不必绑定。

答案 2 :(得分:0)

您使用bind()函数的原因是因为类方法未绑定到类实例对象,在React的情况下,这意味着您无权访问组件的state或{{ 1}}。

使用箭头功能自动绑定到实例对象:props

然后从组件内部的任何地方调用它,如下所示:funcao = () => {...}