0

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');          
}
1
  • 1
    this refers to the class ( App ). But your function is declared ( add function keyword ) outside the class ( intentionally ) . Commented Jun 26, 2020 at 21:56

1 Answer 1

2

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');          
}
Sign up to request clarification or add additional context in comments.

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.