如何在JavaScript中将变量引用传递给函数?

时间:2020-01-14 16:24:35

标签: javascript react-native

假设我有以下反应本机代码,其中我希望基于$internalReference的值,“ press”功能有所不同:

bProps.type

但是问题是const press = bProps.type > 0 ? props.function1(arg1, arg2) : props.function2(arg1, arg2); return <Button onPress={press}></Button>; function1似乎都在按下按钮之前被调用了,而按下按钮似乎没有调用这些功能。有没有办法设置“按下”的值,以便按下按钮可以调用正确的功能?

3 个答案:

答案 0 :(得分:3)

当前,您正在调用该函数并将其返回值分配给RGB listSelection = getSystemColor(SWT.COLOR_LIST_SELECTION);

您需要创建一个 new 函数(当被触发的事件本身调用该函数时,它将使用参数调用要调用的函数)。

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>;

答案 1 :(得分:0)

您可以尝试以下方法:

const press = bProps.type > 0 
    ? () => props.function1(arg1, arg2) 
    : () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;

原始代码必须先评估function1和function2,然后才能评估三元运算符。将它们包装在lambda中意味着需要对lambda进行评估,但这并不意味着它们会立即被调用。

答案 2 :(得分:0)

您可以尝试以下方法:

const press = bProps.type > 0 ? props.function1 : props.function2;
return <Button onPress={() => press(arg1,arg2)}></Button>;
相关问题