Home > front end >  Does writing onPress={onPress()} have anything to do with iife?
Does writing onPress={onPress()} have anything to do with iife?

Time:01-10

If I write onPress below, when I click the button, the console will write test. But if I write onPress(), it writes a test on the console as the page renders. Does writing onPress() have anything to do with iife? Is that why it works without being called the moment the page is rendered?

import React from 'react';
import { Button } from 'react-native';

const Screen = () => {

    const onPress = () =>{
        console.log('test')
    }

    return (
        <Button title='button' onPress={onPress()}/>
    )
};

export default Screen;

CodePudding user response:

No, onPress={onPress()} is not an immediately-invoked function expression (IIFE).¹ It is a function invocation: You're calling onPress and using its return value as the value of the onPress prop. So you see the console message when the component is rendered, since that function call happens during rendering, and you don't see it when pressing the button, because there's no press handler on the button (since onPress doesn't return one).

To have onPress called when the button is pressed, use onPress={onPress} (no () after it):

return (
    <Button title='button' onPress={onPress}/>
);

That assigns your onPress function to the onPress prop, telling the button to call it when the button is pressed.


¹ An IIFE is where you both create and call the function at the same time, like this:

(() => console.log("Hi"))();

The () => console.log("Hi") part creates the function, and the (...)() part calls it.

CodePudding user response:

onPress handler expects a function which will it will execute on press event.

Since in first case, you passing the function object and not executing it, it is working fine.

But in second case, since you executing by yourself, onPress expects that it will receive the function from the output of your onPress event.

You can change it below and it will work

<Button title='button' onPress={() => onPress()}/>

or

<Button title='button' onPress={onPress()}/>


const onPress = () => {
     
    return () => console.log('test'); 
};

CodePudding user response:

No in JS when you want to create an arrow function it should always be pointed out, so now for example

return (
    <Button title='button' onPress={onPress()}/>
  )

will auto execute because it is an assignmentOperation so you can use

return (
    <Button title='button' onPress={() => onPress()}/>
  )
  •  Tags:  
  • Related