在使用ES6和ReactJS时,为什么需要使用bind? [英] Why is it necessary to use bind when working with ES6 and ReactJS?
问题描述
使用ES5开发ReactJS,组件可以表示如下:
Using ES5 development with ReactJS, a component can be stated as the following:
var MyComponent = React.createClass({
alertSomething: function(event) {
alert(event.target);
},
render: function() {
return (
<button onClick={this.alertSomething}>Click Me!</button>
);
}
});
ReactDOM.render(<MyComponent />);
在这个例子中, this
引用了对象本身,这是预期的自然行为。
In this example, the this
references the object itself, which is the expected natural behavior.
问题
我的问题是:
如何使用ES6创建组件?
How you use ES6 to create components?
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
alertSomething(event) {
alert(event.target);
}
render() {
return (
<button onClick={this.alertSomething.bind(this)}>Click Me!</button>
);
}
}
ReactDOM.render(<MyComponent />);
知道在JavaScript中这个
引用了使用new运算符时实例化对象本身,有人可以告诉我使用bind的真正目的是什么?它与React的内部机制有关吗?
Knowing that in JavaScript the this
references the instantiated object itself when using the new operator, someone can tell me what is the real purpose of using bind? It is something related to the internal mechanisms of React?
推荐答案
bind
只是核心的JavaScript。这是绑定事件的工作原理。这不是React概念。
bind
is just core javascript. It's how binding events works. It's not a React concept.
以下文章很好地解释了它。
The following article explains it pretty well.
JavaScript中的有界函数是一个与给定上下文有界的函数。这意味着无论你如何称呼它,呼叫的上下文都将保持不变。
Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same.
要使用常规函数创建有界函数,请使用bind方法。 bind方法将要绑定函数的上下文作为第一个参数。其余参数是将始终传递给此类函数的参数。它返回一个有界函数。
To create a bounded function out of the regular function, the bind method is used. bind method take context to which you want to bind your function as a first argument. The rest of arguments are arguments that will be always passed to such function. It returns a bounded function as a result.
http://reactkungfu.com/2015/07/why-and-how-to-bind-方法在你的反应组件类/
另外,在旁注中,你应该在你的构造函数中完成所有的事件绑定,不在你的渲染方法中。这将阻止多个绑定调用。
Also, on a side note, you should do all of your event binding in your constructor, not in your render method. This will prevent multiple bind calls.
这是关于该主题的另一个有用的信息。他们说:
Here's another good bit of information on the subject. They say:
我们建议您在构造函数中绑定事件处理程序,以便它们仅针对每个实例绑定一次
We recommend that you bind your event handlers in the constructor so they are only bound once for every instance
https ://facebook.github.io/react/docs/reusable-components.html
这篇关于在使用ES6和ReactJS时,为什么需要使用bind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!