1

Suppose I have the following react-native code, in which I want the "press" function to be different based on the value of bProps.type:

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

But the problem is that both function1 and function2 seem to be called before pressing the buttons, and pressing the buttons doesn't seem to call these functions. Is there a way I can set the value of "press" so that pressing the buttons calls the right functions?

3 Answers 3

3

Currently you are calling the function and assigning its return value to press.

You need to create a new function (which will call the function you want to call with arguments when it itself is called by the event being triggered).

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

or

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

or

const press = bProps.type > 0 
    ? () => props.function1(arg1, arg2)
    : () => props.function2(arg1, arg2);
return <Button onPress={press}></Button>;
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this:

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

The original code had to evaluate function1 and function2 before it could evaluate the ternary operator. Wrapping them in lambdas means the lambdas need to be evaluated, but that doesn't mean they are immediately called.

Comments

0

You can try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.