gpt4 book ai didi

javascript - bind 如何自动将事件参数传递给事件处理程序?

转载 作者:行者123 更新时间:2023-11-30 19:38:46 26 4
gpt4 key购买 nike

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>

In both cases, the e argument representing the React event will be passed as a second argument after the ID. With an arrow function, we have to pass it explicitly, but with bind any further arguments are automatically forwarded.

因此,当使用 bind 时,事件作为参数传递给回调中的事件处理程序——这是如何/为什么起作用的?

最佳答案

如果您检查 polyfill 中的绑定(bind),您将得到答案,我的意思是绑定(bind)到底做了什么。

Bind 基本上返回一个新函数,每当您调用该函数(由 bind 返回)时,它会合并所有参数(绑定(bind)期间传递的参数和传递给 bind 返回的函数的参数),然后将其传递给原始函数。

检查这个polyfill (Source- MDN) :

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);
};
};
})();

关于javascript - bind 如何自动将事件参数传递给事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55644769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com