![](/img/trans.png)
[英]Javascript: How do I pass the value (not the reference) of a variable to a function?
[英]How to pass a variable reference to a function in JavaScript?
假設我有以下 react-native 代碼,其中我希望“press”函數根據bProps.type
的值而bProps.type
:
const press = bProps.type > 0
? props.function1(arg1, arg2)
: props.function2(arg1, arg2);
return <Button onPress={press}></Button>;
但問題是function1
和function2
似乎都是在按下按鈕之前被調用的,而按下按鈕似乎並沒有調用這些函數。 有沒有辦法設置“按下”的值,以便按下按鈕調用正確的功能?
當前,您正在調用該函數並將其返回值分配給press
。
您需要創建一個新函數(當它本身被觸發的事件調用時,它將使用參數調用您要調用的函數)。
const press = bProps.type > 0
? function() { props.function1(arg1, arg2) }
: function() { props.function2(arg1, arg2) };
return <Button onPress={press}></Button>;
或者
const press = bProps.type > 0
? props.function1.bind(null, arg1, arg2) }
: props.function2.bind(null, arg1, arg2) };
return <Button onPress={press}></Button>;
或者
const press = bProps.type > 0
? () => props.function1(arg1, arg2)
: () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;
你可以試試這個:
const press = bProps.type > 0
? () => props.function1(arg1, arg2)
: () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;
原始代碼必須先計算 function1 和 function2,然后才能計算三元運算符。 將它們包裝在 lambdas 中意味着需要評估 lambdas,但這並不意味着它們會立即被調用。
你可以試試這個:
const press = bProps.type > 0 ? props.function1 : props.function2;
return <Button onPress={() => press(arg1,arg2)}></Button>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.