3

This might be an easy question, but I'm new to React-Native and I'm totally stuck right now.

How do I call function2 from function1?

This is what I've tried, but when pressing the first button it renders an error that says:

Undefined is not a function (evaluating 'this.function2()')

import React, { Component } from 'react';
import {
AppRegistry,
View,
Image,
TouchableOpacity,
} from 'react-native';

export default class Example extends Component {

    function1(){
        console.log('function1() called');
        ...
        this.function2();
    };

    function2() {
        console.log('function2() called');
        ...
    };

    render() {
        return (
            <View>
                <TouchableOpacity onPress={this.function1}>
                    <Image source={require('../../../assets/img/button.png')} />
                </TouchableOpacity>

                <TouchableOpacity onPress={this.function2}>
                    <Image source={require('../../../assets/img/button.png')} />
                </TouchableOpacity>
            </View>
        );
    };
}

AppRegistry.registerComponent('Example', () => Example);
2
  • What about calling function2() directly? Commented Sep 2, 2017 at 21:33
  • @user10089632 Because you sometimes might want to execute code in function1() as well, but sometimes only in function2(). It reduces redundancy. See the edited code in the post. Commented Sep 3, 2017 at 2:28

2 Answers 2

4

Try this,

<TouchableOpacity onPress={() => this.function1()}>
      <Image source={require('../../../assets/img/button.png')} />
</TouchableOpacity>

fat arrow functions have a shorter syntax compared to function expressions and lexically bind the this value. Arrow functions are always anonymous and effectively turn function (arguments) { expression } into arguments => expression. If using an expression after an arrow, the return is implicit, so no return is required.

Sign up to request clarification or add additional context in comments.

1 Comment

I see! I thought it had to do with the scope and the binding. Thank you for your help.
4

if the function is a callback and will pass to another component, you should bind them in your component constructer.

constructor(props) {
  super(props);

  this.function1 = this.function1.bind(this);
  this.function2 = this.function2.bind(this);
}

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.