[英]How to call multiple instance of the SAME function with different arguments in onClick React?
[英]In React, how to call multiple functions with their own arguments?
我想在點擊時通過道具調用兩個函數。 請注意,它們都需要自己的參數。 在 Stack Overflow 上搜索了一下之后,我找到了這個解決方案:
onclick={()=>{ f1(); f2() }}
所以我按如下方式實現了我的:
onClick={() => {f1(arg); f2.bind(this, arg)}}
但是第二個函數永遠不會被調用。 誰能解釋為什么這不起作用? 我假設它有一些具有約束力的問題?
f1 在父組件中:
f1(arg, event)
{
event.preventDefault();
// so on...
}
f2 也在父參數中,如下所示:
f2(arg)
{
// do something with the argument
}
他們正在傳遞給子組件
render()
{
const { f2, arg, f1 } = this.props;
return(
<button onClick={() => {f2(arg); f1.call(this, arg)}}>
)
}
第二個函數不起作用,因為您實際上並沒有使用bind調用函數,您只是為將來的函數調用綁定了作用域。 如果要調用具有指定范圍的函數,請使用call或apply
關於它們的更多信息: https : //stackoverflow.com/a/15455043/5709697
編輯
對於您的情況,您可以像這樣調用第二個函數:
onClick={(e) => {f1(e); f2.call(this, e)}}
沙箱鏈接: https : //codesandbox.io/s/509o1lxjp
試試這個方法
onClick={(arg)=>{ this.f1(arg); this.f2(this, arg) }}
或者進行如下單獨的函數調用。
onClick={(arg)=>{ this.f1(arg) }}
f1(values){
this.f2(values);
}
您可以將這兩種方法稱為
onClick={() =>{ this.f1(arg);this.f2(arg)}}
因為您不是在調用第二種方法,只是使用 bind 創建它。
當您將() => {}
與 onClik 一起使用時,上下文將由箭頭函數維護,之后您無需綁定這兩個函數。
像這樣寫:
onClick={(e) => {
this.f1(e, arg1, arg2, arg3); // use f1, if function is defined outside of class
this.f2(e, arg2)
}}
f1 (e, arg1, arg2, arg3) {
e.preventDefault();
console.log(arg1, arg2, arg3)
}
f2 (e, arg2) {
e.preventDefault();
console.log(arg2)
}
檢查MDN 文檔: The bind() method creates a new function.
檢查這些答案以獲取有關綁定的更多詳細信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.