React文档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
时,该事件将作为参数传递给回调中的事件处理程序-它如何/为什么起作用?
答案 0 :(得分:1)
如果您检查polyfill
的绑定,您将得到答案,我的意思是确切的绑定是什么。
Bind基本上会返回一个新函数,无论何时调用该函数(由bind返回),它将合并所有参数(绑定期间传递的参数和传递给bind返回的函数的参数),然后将其传递给原始函数。 / p>
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);
};
};
})();