React docs page on Handling Events说:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
在这两种情况下,表示React事件的e参数将作为ID之后的第二个参数传递。使用箭头函数,我们必须显式传递它,但是使用bind,任何其他参数都会自动转发。
因此,当使用bind
时,事件将作为参数传递给回调中的事件处理程序 - 如何/为什么这样做?
如果你检查polyfill
是否绑定,你会得到答案,我的意思是完全绑定做什么。
绑定基本上返回一个新函数,每当你调用该函数(由bind返回)时,它将合并所有参数(绑定期间传递的参数和传递给bind返回的函数的参数),然后将其传递给原始函数。
if (!Function.prototype.bind) (function(){
var ArrayPrototypeSlice = Array.prototype.slice;
Function.prototype.bind = function() {
var thatFunc = this, thatArg = arguments[0];
// ↓↓↓↓↓↓↓↓↓↓↓ argument bound to function
var args = ArrayPrototypeSlice.call(arguments, 1);
if (typeof thatFunc !== 'function') {
throw new TypeError('Function.prototype.bind - ' + 'what is trying to be bound is not callable');
}
return function(){
// ↓↓↓↓↓↓↓↓↓↓ check here, this line is basically merging all the arguments
args.push.apply(args, arguments);
// ↓↓↓↓↓↓↓↓↓↓ here, it will call the function with particular context and all the parameters
return thatFunc.apply(thatArg, args);
};
};
})();