gorp88
gorp88

Reputation: 105

Calling function in react native outside component

My requirement

I am calling my function placed outside of the component and view in react native, but it throws errors saying the _this.myfunction is undefined. Its clearly not getting the reference for the function. Is it possible to achieve such feature in react native.

class  App extends React.Component {

    constructor(props) {
        super(props);
    }

   render () {
       return (
            <View style={styles.container}>
                <Button onPress={() => this.Myfunction()} style={styles.Button} title="Button"/>                            
            </View>
       );
     }
 }       

Myfunction () {
  alert('clicked');          
}

Upvotes: 0

Views: 1064

Answers (1)

Siddharth
Siddharth

Reputation: 1270

Since you've defined the function outside of the class, you don't need to refer it by this. You can simply write onPress={() => Myfunction()} or onPress={Myfunction}

Also your function's syntax is wrong, add the function keyword before it

function Myfunction () {
  alert('clicked');          
}

Upvotes: 2

Related Questions